MDL-30514 registration: table aliases don't use AS keyword
[moodle.git] / course / lib.php
blobbc4d0722beaef0263c56843a663f3864852b42c2
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 * Set highlighted section. Only one section can be highlighted at the time.
1347 * @param int $courseid course id
1348 * @param int $marker highlight section with this number, 0 means remove higlightin
1349 * @return void
1351 function course_set_marker($courseid, $marker) {
1352 global $DB;
1353 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
1357 * For a given course section, marks it visible or hidden,
1358 * and does the same for every activity in that section
1360 function set_section_visible($courseid, $sectionnumber, $visibility) {
1361 global $DB;
1363 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1364 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1365 if (!empty($section->sequence)) {
1366 $modules = explode(",", $section->sequence);
1367 foreach ($modules as $moduleid) {
1368 set_coursemodule_visible($moduleid, $visibility, true);
1371 rebuild_course_cache($courseid);
1376 * Obtains shared data that is used in print_section when displaying a
1377 * course-module entry.
1379 * Calls format_text or format_string as appropriate, and obtains the correct icon.
1381 * This data is also used in other areas of the code.
1382 * @param cm_info $cm Course-module data (must come from get_fast_modinfo)
1383 * @param object $course Moodle course object
1384 * @return array An array with the following values in this order:
1385 * $content (optional extra content for after link),
1386 * $instancename (text of link)
1388 function get_print_section_cm_text(cm_info $cm, $course) {
1389 global $OUTPUT;
1391 // Get content from modinfo if specified. Content displays either
1392 // in addition to the standard link (below), or replaces it if
1393 // the link is turned off by setting ->url to null.
1394 if (($content = $cm->get_content()) !== '') {
1395 // Improve filter performance by preloading filter setttings for all
1396 // activities on the course (this does nothing if called multiple
1397 // times)
1398 filter_preload_activities($cm->get_modinfo());
1400 // Get module context
1401 $modulecontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1402 $labelformatoptions = new stdClass();
1403 $labelformatoptions->noclean = true;
1404 $labelformatoptions->overflowdiv = true;
1405 $labelformatoptions->context = $modulecontext;
1406 $content = format_text($content, FORMAT_HTML, $labelformatoptions);
1407 } else {
1408 $content = '';
1411 // Get course context
1412 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1413 $stringoptions = new stdClass;
1414 $stringoptions->context = $coursecontext;
1415 $instancename = format_string($cm->name, true, $stringoptions);
1416 return array($content, $instancename);
1420 * Prints a section full of activity modules
1422 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1423 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1425 static $initialised;
1427 static $groupbuttons;
1428 static $groupbuttonslink;
1429 static $isediting;
1430 static $ismoving;
1431 static $strmovehere;
1432 static $strmovefull;
1433 static $strunreadpostsone;
1434 static $groupings;
1435 static $modulenames;
1437 if (!isset($initialised)) {
1438 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1439 $groupbuttonslink = (!$course->groupmodeforce);
1440 $isediting = $PAGE->user_is_editing();
1441 $ismoving = $isediting && ismoving($course->id);
1442 if ($ismoving) {
1443 $strmovehere = get_string("movehere");
1444 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1446 $modulenames = array();
1447 $initialised = true;
1450 $tl = textlib_get_instance();
1452 $modinfo = get_fast_modinfo($course);
1453 $completioninfo = new completion_info($course);
1455 //Accessibility: replace table with list <ul>, but don't output empty list.
1456 if (!empty($section->sequence)) {
1458 // Fix bug #5027, don't want style=\"width:$width\".
1459 echo "<ul class=\"section img-text\">\n";
1460 $sectionmods = explode(",", $section->sequence);
1462 foreach ($sectionmods as $modnumber) {
1463 if (empty($mods[$modnumber])) {
1464 continue;
1468 * @var cm_info
1470 $mod = $mods[$modnumber];
1472 if ($ismoving and $mod->id == $USER->activitycopy) {
1473 // do not display moving mod
1474 continue;
1477 if (isset($modinfo->cms[$modnumber])) {
1478 // We can continue (because it will not be displayed at all)
1479 // if:
1480 // 1) The activity is not visible to users
1481 // and
1482 // 2a) The 'showavailability' option is not set (if that is set,
1483 // we need to display the activity so we can show
1484 // availability info)
1485 // or
1486 // 2b) The 'availableinfo' is empty, i.e. the activity was
1487 // hidden in a way that leaves no info, such as using the
1488 // eye icon.
1489 if (!$modinfo->cms[$modnumber]->uservisible &&
1490 (empty($modinfo->cms[$modnumber]->showavailability) ||
1491 empty($modinfo->cms[$modnumber]->availableinfo))) {
1492 // visibility shortcut
1493 continue;
1495 } else {
1496 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1497 // module not installed
1498 continue;
1500 if (!coursemodule_visible_for_user($mod) &&
1501 empty($mod->showavailability)) {
1502 // full visibility check
1503 continue;
1507 if (!isset($modulenames[$mod->modname])) {
1508 $modulenames[$mod->modname] = get_string('modulename', $mod->modname);
1510 $modulename = $modulenames[$mod->modname];
1512 // In some cases the activity is visible to user, but it is
1513 // dimmed. This is done if viewhiddenactivities is true and if:
1514 // 1. the activity is not visible, or
1515 // 2. the activity has dates set which do not include current, or
1516 // 3. the activity has any other conditions set (regardless of whether
1517 // current user meets them)
1518 $modcontext = context_module::instance($mod->id);
1519 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
1520 $accessiblebutdim = false;
1521 if ($canviewhidden) {
1522 $accessiblebutdim = !$mod->visible;
1523 if (!empty($CFG->enableavailability)) {
1524 $accessiblebutdim = $accessiblebutdim ||
1525 $mod->availablefrom > time() ||
1526 ($mod->availableuntil && $mod->availableuntil < time()) ||
1527 count($mod->conditionsgrade) > 0 ||
1528 count($mod->conditionscompletion) > 0;
1532 $liclasses = array();
1533 $liclasses[] = 'activity';
1534 $liclasses[] = $mod->modname;
1535 $liclasses[] = 'modtype_'.$mod->modname;
1536 $extraclasses = $mod->get_extra_classes();
1537 if ($extraclasses) {
1538 $liclasses = array_merge($liclasses, explode(' ', $extraclasses));
1540 echo html_writer::start_tag('li', array('class'=>join(' ', $liclasses), 'id'=>'module-'.$modnumber));
1541 if ($ismoving) {
1542 echo '<a title="'.$strmovefull.'"'.
1543 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1544 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1545 ' alt="'.$strmovehere.'" /></a><br />
1549 $classes = array('mod-indent');
1550 if (!empty($mod->indent)) {
1551 $classes[] = 'mod-indent-'.$mod->indent;
1552 if ($mod->indent > 15) {
1553 $classes[] = 'mod-indent-huge';
1556 echo html_writer::start_tag('div', array('class'=>join(' ', $classes)));
1558 // Get data about this course-module
1559 list($content, $instancename) =
1560 get_print_section_cm_text($modinfo->cms[$modnumber], $course);
1562 //Accessibility: for files get description via icon, this is very ugly hack!
1563 $altname = '';
1564 $altname = $mod->modfullname;
1565 if (!empty($customicon)) {
1566 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1567 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1568 $mimetype = mimeinfo_from_icon('type', $customicon);
1569 $altname = get_mimetype_description($mimetype);
1572 // Avoid unnecessary duplication: if e.g. a forum name already
1573 // includes the word forum (or Forum, etc) then it is unhelpful
1574 // to include that in the accessible description that is added.
1575 if (false !== strpos($tl->strtolower($instancename),
1576 $tl->strtolower($altname))) {
1577 $altname = '';
1579 // File type after name, for alphabetic lists (screen reader).
1580 if ($altname) {
1581 $altname = get_accesshide(' '.$altname);
1584 // We may be displaying this just in order to show information
1585 // about visibility, without the actual link
1586 $contentpart = '';
1587 if ($mod->uservisible) {
1588 // Nope - in this case the link is fully working for user
1589 $linkclasses = '';
1590 $textclasses = '';
1591 if ($accessiblebutdim) {
1592 $linkclasses .= ' dimmed';
1593 $textclasses .= ' dimmed_text';
1594 $accesstext = '<span class="accesshide">'.
1595 get_string('hiddenfromstudents').': </span>';
1596 } else {
1597 $accesstext = '';
1599 if ($linkclasses) {
1600 $linkcss = 'class="' . trim($linkclasses) . '" ';
1601 } else {
1602 $linkcss = '';
1604 if ($textclasses) {
1605 $textcss = 'class="' . trim($textclasses) . '" ';
1606 } else {
1607 $textcss = '';
1610 // Get on-click attribute value if specified
1611 $onclick = $mod->get_on_click();
1612 if ($onclick) {
1613 $onclick = ' onclick="' . $onclick . '"';
1616 if ($url = $mod->get_url()) {
1617 // Display link itself
1618 echo '<a ' . $linkcss . $mod->extra . $onclick .
1619 ' href="' . $url . '"><img src="' . $mod->get_icon_url() .
1620 '" class="activityicon" alt="" /> ' .
1621 $accesstext . '<span class="instancename">' .
1622 $instancename . $altname . '</span></a>';
1624 // If specified, display extra content after link
1625 if ($content) {
1626 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1627 '">' . $content . '</div>';
1629 } else {
1630 // No link, so display only content
1631 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1632 $accesstext . $content . '</div>';
1635 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1636 if (!isset($groupings)) {
1637 $groupings = groups_get_all_groupings($course->id);
1639 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1641 } else {
1642 $textclasses = $extraclasses;
1643 $textclasses .= ' dimmed_text';
1644 if ($textclasses) {
1645 $textcss = 'class="' . trim($textclasses) . '" ';
1646 } else {
1647 $textcss = '';
1649 $accesstext = '<span class="accesshide">' .
1650 get_string('notavailableyet', 'condition') .
1651 ': </span>';
1653 if ($url = $mod->get_url()) {
1654 // Display greyed-out text of link
1655 echo '<div ' . $textcss . $mod->extra .
1656 ' >' . '<img src="' . $mod->get_icon_url() .
1657 '" class="activityicon" alt="" /> <span>'. $instancename . $altname .
1658 '</span></div>';
1660 // Do not display content after link when it is greyed out like this.
1661 } else {
1662 // No link, so display only content (also greyed)
1663 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1664 $accesstext . $content . '</div>';
1668 // Module can put text after the link (e.g. forum unread)
1669 echo $mod->get_after_link();
1671 // If there is content but NO link (eg label), then display the
1672 // content here (BEFORE any icons). In this case cons must be
1673 // displayed after the content so that it makes more sense visually
1674 // and for accessibility reasons, e.g. if you have a one-line label
1675 // it should work similarly (at least in terms of ordering) to an
1676 // activity.
1677 if (empty($url)) {
1678 echo $contentpart;
1681 if ($isediting) {
1682 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1683 if (! $mod->groupmodelink = $groupbuttonslink) {
1684 $mod->groupmode = $course->groupmode;
1687 } else {
1688 $mod->groupmode = false;
1690 echo '&nbsp;&nbsp;';
1691 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1692 echo $mod->get_after_edit_icons();
1695 // Completion
1696 $completion = $hidecompletion
1697 ? COMPLETION_TRACKING_NONE
1698 : $completioninfo->is_enabled($mod);
1699 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1700 !isguestuser() && $mod->uservisible) {
1701 $completiondata = $completioninfo->get_data($mod,true);
1702 $completionicon = '';
1703 if ($isediting) {
1704 switch ($completion) {
1705 case COMPLETION_TRACKING_MANUAL :
1706 $completionicon = 'manual-enabled'; break;
1707 case COMPLETION_TRACKING_AUTOMATIC :
1708 $completionicon = 'auto-enabled'; break;
1709 default: // wtf
1711 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1712 switch($completiondata->completionstate) {
1713 case COMPLETION_INCOMPLETE:
1714 $completionicon = 'manual-n'; break;
1715 case COMPLETION_COMPLETE:
1716 $completionicon = 'manual-y'; break;
1718 } else { // Automatic
1719 switch($completiondata->completionstate) {
1720 case COMPLETION_INCOMPLETE:
1721 $completionicon = 'auto-n'; break;
1722 case COMPLETION_COMPLETE:
1723 $completionicon = 'auto-y'; break;
1724 case COMPLETION_COMPLETE_PASS:
1725 $completionicon = 'auto-pass'; break;
1726 case COMPLETION_COMPLETE_FAIL:
1727 $completionicon = 'auto-fail'; break;
1730 if ($completionicon) {
1731 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1732 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1733 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1734 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1735 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1736 $newstate =
1737 $completiondata->completionstate==COMPLETION_COMPLETE
1738 ? COMPLETION_INCOMPLETE
1739 : COMPLETION_COMPLETE;
1740 // In manual mode the icon is a toggle form...
1742 // If this completion state is used by the
1743 // conditional activities system, we need to turn
1744 // off the JS.
1745 if (!empty($CFG->enableavailability) &&
1746 condition_info::completion_value_used_as_condition($course, $mod)) {
1747 $extraclass = ' preventjs';
1748 } else {
1749 $extraclass = '';
1751 echo "
1752 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1753 <input type='hidden' name='id' value='{$mod->id}' />
1754 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1755 <input type='hidden' name='sesskey' value='".sesskey()."' />
1756 <input type='hidden' name='completionstate' value='$newstate' />
1757 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1758 </div></form>";
1759 } else {
1760 // In auto mode, or when editing, the icon is just an image
1761 echo "<span class='autocompletion'>";
1762 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1767 // If there is content AND a link, then display the content here
1768 // (AFTER any icons). Otherwise it was displayed before
1769 if (!empty($url)) {
1770 echo $contentpart;
1773 // Show availability information (for someone who isn't allowed to
1774 // see the activity itself, or for staff)
1775 if (!$mod->uservisible) {
1776 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1777 } else if ($canviewhidden && !empty($CFG->enableavailability) && $mod->visible) {
1778 $ci = new condition_info($mod);
1779 $fullinfo = $ci->get_full_information();
1780 if($fullinfo) {
1781 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1782 ? 'userrestriction_visible'
1783 : 'userrestriction_hidden','condition',
1784 $fullinfo).'</div>';
1788 echo html_writer::end_tag('div');
1789 echo html_writer::end_tag('li')."\n";
1792 } elseif ($ismoving) {
1793 echo "<ul class=\"section\">\n";
1796 if ($ismoving) {
1797 echo '<li><a title="'.$strmovefull.'"'.
1798 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1799 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1800 ' alt="'.$strmovehere.'" /></a></li>
1803 if (!empty($section->sequence) || $ismoving) {
1804 echo "</ul><!--class='section'-->\n\n";
1809 * Prints the menus to add activities and resources.
1811 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1812 global $CFG, $OUTPUT;
1814 // check to see if user can add menus
1815 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1816 return false;
1819 $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
1821 $resources = array();
1822 $activities = array();
1824 foreach($modnames as $modname=>$modnamestr) {
1825 if (!course_allowed_module($course, $modname)) {
1826 continue;
1829 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1830 if (!file_exists($libfile)) {
1831 continue;
1833 include_once($libfile);
1834 $gettypesfunc = $modname.'_get_types';
1835 if (function_exists($gettypesfunc)) {
1836 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1837 if ($types = $gettypesfunc()) {
1838 $menu = array();
1839 $atype = null;
1840 $groupname = null;
1841 foreach($types as $type) {
1842 if ($type->typestr === '--') {
1843 continue;
1845 if (strpos($type->typestr, '--') === 0) {
1846 $groupname = str_replace('--', '', $type->typestr);
1847 continue;
1849 $type->type = str_replace('&amp;', '&', $type->type);
1850 if ($type->modclass == MOD_CLASS_RESOURCE) {
1851 $atype = MOD_CLASS_RESOURCE;
1853 $menu[$urlbase.$type->type] = $type->typestr;
1855 if (!is_null($groupname)) {
1856 if ($atype == MOD_CLASS_RESOURCE) {
1857 $resources[] = array($groupname=>$menu);
1858 } else {
1859 $activities[] = array($groupname=>$menu);
1861 } else {
1862 if ($atype == MOD_CLASS_RESOURCE) {
1863 $resources = array_merge($resources, $menu);
1864 } else {
1865 $activities = array_merge($activities, $menu);
1869 } else {
1870 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1871 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1872 $resources[$urlbase.$modname] = $modnamestr;
1873 } else {
1874 // all other archetypes are considered activity
1875 $activities[$urlbase.$modname] = $modnamestr;
1880 $straddactivity = get_string('addactivity');
1881 $straddresource = get_string('addresource');
1883 $output = '<div class="section_add_menus">';
1885 if (!$vertical) {
1886 $output .= '<div class="horizontal">';
1889 if (!empty($resources)) {
1890 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1891 $select->set_help_icon('resources');
1892 $output .= $OUTPUT->render($select);
1895 if (!empty($activities)) {
1896 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1897 $select->set_help_icon('activities');
1898 $output .= $OUTPUT->render($select);
1901 if (!$vertical) {
1902 $output .= '</div>';
1905 $output .= '</div>';
1907 if ($return) {
1908 return $output;
1909 } else {
1910 echo $output;
1915 * Return the course category context for the category with id $categoryid, except
1916 * that if $categoryid is 0, return the system context.
1918 * @param integer $categoryid a category id or 0.
1919 * @return object the corresponding context
1921 function get_category_or_system_context($categoryid) {
1922 if ($categoryid) {
1923 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1924 } else {
1925 return get_context_instance(CONTEXT_SYSTEM);
1930 * Gets the child categories of a given courses category. Uses a static cache
1931 * to make repeat calls efficient.
1933 * @param int $parentid the id of a course category.
1934 * @return array all the child course categories.
1936 function get_child_categories($parentid) {
1937 static $allcategories = null;
1939 // only fill in this variable the first time
1940 if (null == $allcategories) {
1941 $allcategories = array();
1943 $categories = get_categories();
1944 foreach ($categories as $category) {
1945 if (empty($allcategories[$category->parent])) {
1946 $allcategories[$category->parent] = array();
1948 $allcategories[$category->parent][] = $category;
1952 if (empty($allcategories[$parentid])) {
1953 return array();
1954 } else {
1955 return $allcategories[$parentid];
1960 * This function recursively travels the categories, building up a nice list
1961 * for display. It also makes an array that list all the parents for each
1962 * category.
1964 * For example, if you have a tree of categories like:
1965 * Miscellaneous (id = 1)
1966 * Subcategory (id = 2)
1967 * Sub-subcategory (id = 4)
1968 * Other category (id = 3)
1969 * Then after calling this function you will have
1970 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1971 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1972 * 3 => 'Other category');
1973 * $parents = array(2 => array(1), 4 => array(1, 2));
1975 * If you specify $requiredcapability, then only categories where the current
1976 * user has that capability will be added to $list, although all categories
1977 * will still be added to $parents, and if you only have $requiredcapability
1978 * in a child category, not the parent, then the child catgegory will still be
1979 * included.
1981 * If you specify the option $excluded, then that category, and all its children,
1982 * are omitted from the tree. This is useful when you are doing something like
1983 * moving categories, where you do not want to allow people to move a category
1984 * to be the child of itself.
1986 * @param array $list For output, accumulates an array categoryid => full category path name
1987 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1988 * @param string/array $requiredcapability if given, only categories where the current
1989 * user has this capability will be added to $list. Can also be an array of capabilities,
1990 * in which case they are all required.
1991 * @param integer $excludeid Omit this category and its children from the lists built.
1992 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1993 * @param string $path For internal use, as part of recursive calls.
1995 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1996 $excludeid = 0, $category = NULL, $path = "") {
1998 // initialize the arrays if needed
1999 if (!is_array($list)) {
2000 $list = array();
2002 if (!is_array($parents)) {
2003 $parents = array();
2006 if (empty($category)) {
2007 // Start at the top level.
2008 $category = new stdClass;
2009 $category->id = 0;
2010 } else {
2011 // This is the excluded category, don't include it.
2012 if ($excludeid > 0 && $excludeid == $category->id) {
2013 return;
2016 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2017 $categoryname = format_string($category->name, true, array('context' => $context));
2019 // Update $path.
2020 if ($path) {
2021 $path = $path.' / '.$categoryname;
2022 } else {
2023 $path = $categoryname;
2026 // Add this category to $list, if the permissions check out.
2027 if (empty($requiredcapability)) {
2028 $list[$category->id] = $path;
2030 } else {
2031 $requiredcapability = (array)$requiredcapability;
2032 if (has_all_capabilities($requiredcapability, $context)) {
2033 $list[$category->id] = $path;
2038 // Add all the children recursively, while updating the parents array.
2039 if ($categories = get_child_categories($category->id)) {
2040 foreach ($categories as $cat) {
2041 if (!empty($category->id)) {
2042 if (isset($parents[$category->id])) {
2043 $parents[$cat->id] = $parents[$category->id];
2045 $parents[$cat->id][] = $category->id;
2047 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2053 * This function generates a structured array of courses and categories.
2055 * The depth of categories is limited by $CFG->maxcategorydepth however there
2056 * is no limit on the number of courses!
2058 * Suitable for use with the course renderers course_category_tree method:
2059 * $renderer = $PAGE->get_renderer('core','course');
2060 * echo $renderer->course_category_tree(get_course_category_tree());
2062 * @global moodle_database $DB
2063 * @param int $id
2064 * @param int $depth
2066 function get_course_category_tree($id = 0, $depth = 0) {
2067 global $DB, $CFG;
2068 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2069 $categories = get_child_categories($id);
2070 $categoryids = array();
2071 foreach ($categories as $key => &$category) {
2072 if (!$category->visible && !$viewhiddencats) {
2073 unset($categories[$key]);
2074 continue;
2076 $categoryids[$category->id] = $category;
2077 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2078 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2079 foreach ($subcategories as $subid=>$subcat) {
2080 $categoryids[$subid] = $subcat;
2082 $category->courses = array();
2086 if ($depth > 0) {
2087 // This is a recursive call so return the required array
2088 return array($categories, $categoryids);
2091 if (empty($categoryids)) {
2092 // No categories available (probably all hidden).
2093 return array();
2096 // The depth is 0 this function has just been called so we can finish it off
2098 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2099 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2100 $sql = "SELECT
2101 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2102 $ccselect
2103 FROM {course} c
2104 $ccjoin
2105 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2106 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2107 // loop throught them
2108 foreach ($courses as $course) {
2109 if ($course->id == SITEID) {
2110 continue;
2112 context_instance_preload($course);
2113 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2114 $categoryids[$course->category]->courses[$course->id] = $course;
2118 return $categories;
2122 * Recursive function to print out all the categories in a nice format
2123 * with or without courses included
2125 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2126 global $CFG;
2128 // maxcategorydepth == 0 meant no limit
2129 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2130 return;
2133 if (!$displaylist) {
2134 make_categories_list($displaylist, $parentslist);
2137 if ($category) {
2138 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2139 print_category_info($category, $depth, $showcourses);
2140 } else {
2141 return; // Don't bother printing children of invisible categories
2144 } else {
2145 $category = new stdClass();
2146 $category->id = "0";
2149 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2150 $countcats = count($categories);
2151 $count = 0;
2152 $first = true;
2153 $last = false;
2154 foreach ($categories as $cat) {
2155 $count++;
2156 if ($count == $countcats) {
2157 $last = true;
2159 $up = $first ? false : true;
2160 $down = $last ? false : true;
2161 $first = false;
2163 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2169 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2171 function make_categories_options() {
2172 make_categories_list($cats,$parents);
2173 foreach ($cats as $key => $value) {
2174 if (array_key_exists($key,$parents)) {
2175 if ($indent = count($parents[$key])) {
2176 for ($i = 0; $i < $indent; $i++) {
2177 $cats[$key] = '&nbsp;'.$cats[$key];
2182 return $cats;
2186 * Prints the category info in indented fashion
2187 * This function is only used by print_whole_category_list() above
2189 function print_category_info($category, $depth=0, $showcourses = false) {
2190 global $CFG, $DB, $OUTPUT;
2192 $strsummary = get_string('summary');
2194 $catlinkcss = null;
2195 if (!$category->visible) {
2196 $catlinkcss = array('class'=>'dimmed');
2198 static $coursecount = null;
2199 if (null === $coursecount) {
2200 // only need to check this once
2201 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2204 if ($showcourses and $coursecount) {
2205 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2206 } else {
2207 $catimage = "&nbsp;";
2210 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2211 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2212 $fullname = format_string($category->name, true, array('context' => $context));
2214 if ($showcourses and $coursecount) {
2215 echo '<div class="categorylist clearfix">';
2216 $cat = '';
2217 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2218 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2219 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2221 $html = '';
2222 if ($depth > 0) {
2223 for ($i=0; $i< $depth; $i++) {
2224 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2225 $cat = '';
2227 } else {
2228 $html = $cat;
2230 echo html_writer::tag('div', $html, array('class'=>'category'));
2231 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2233 // does the depth exceed maxcategorydepth
2234 // maxcategorydepth == 0 or unset meant no limit
2235 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2236 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2237 foreach ($courses as $course) {
2238 $linkcss = null;
2239 if (!$course->visible) {
2240 $linkcss = array('class'=>'dimmed');
2243 $coursename = get_course_display_name_for_list($course);
2244 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2246 // print enrol info
2247 $courseicon = '';
2248 if ($icons = enrol_get_course_info_icons($course)) {
2249 foreach ($icons as $pix_icon) {
2250 $courseicon = $OUTPUT->render($pix_icon).' ';
2254 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2256 if ($course->summary) {
2257 $link = new moodle_url('/course/info.php?id='.$course->id);
2258 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2259 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2260 array('title'=>$strsummary));
2262 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2265 $html = '';
2266 for ($i=0; $i <= $depth; $i++) {
2267 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2268 $coursecontent = '';
2270 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2273 echo '</div>';
2274 } else {
2275 echo '<div class="categorylist">';
2276 $html = '';
2277 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2278 if (count($courses) > 0) {
2279 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2282 if ($depth > 0) {
2283 for ($i=0; $i< $depth; $i++) {
2284 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2285 $cat = '';
2287 } else {
2288 $html = $cat;
2291 echo html_writer::tag('div', $html, array('class'=>'category'));
2292 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2293 echo '</div>';
2298 * Print the buttons relating to course requests.
2300 * @param object $systemcontext the system context.
2302 function print_course_request_buttons($systemcontext) {
2303 global $CFG, $DB, $OUTPUT;
2304 if (empty($CFG->enablecourserequests)) {
2305 return;
2307 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2308 /// Print a button to request a new course
2309 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2311 /// Print a button to manage pending requests
2312 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2313 $disabled = !$DB->record_exists('course_request', array());
2314 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2319 * Does the user have permission to edit things in this category?
2321 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2322 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2324 function can_edit_in_category($categoryid = 0) {
2325 $context = get_category_or_system_context($categoryid);
2326 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2330 * Prints the turn editing on/off button on course/index.php or course/category.php.
2332 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2333 * @return string HTML of the editing button, or empty string, if this user is not allowed
2334 * to see it.
2336 function update_category_button($categoryid = 0) {
2337 global $CFG, $PAGE, $OUTPUT;
2339 // Check permissions.
2340 if (!can_edit_in_category($categoryid)) {
2341 return '';
2344 // Work out the appropriate action.
2345 if ($PAGE->user_is_editing()) {
2346 $label = get_string('turneditingoff');
2347 $edit = 'off';
2348 } else {
2349 $label = get_string('turneditingon');
2350 $edit = 'on';
2353 // Generate the button HTML.
2354 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2355 if ($categoryid) {
2356 $options['id'] = $categoryid;
2357 $page = 'category.php';
2358 } else {
2359 $page = 'index.php';
2361 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2365 * Category is 0 (for all courses) or an object
2367 function print_courses($category) {
2368 global $CFG, $OUTPUT;
2370 if (!is_object($category) && $category==0) {
2371 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2372 if (is_array($categories) && count($categories) == 1) {
2373 $category = array_shift($categories);
2374 $courses = get_courses_wmanagers($category->id,
2375 'c.sortorder ASC',
2376 array('summary','summaryformat'));
2377 } else {
2378 $courses = get_courses_wmanagers('all',
2379 'c.sortorder ASC',
2380 array('summary','summaryformat'));
2382 unset($categories);
2383 } else {
2384 $courses = get_courses_wmanagers($category->id,
2385 'c.sortorder ASC',
2386 array('summary','summaryformat'));
2389 if ($courses) {
2390 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2391 foreach ($courses as $course) {
2392 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2393 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2394 echo html_writer::start_tag('li');
2395 print_course($course);
2396 echo html_writer::end_tag('li');
2399 echo html_writer::end_tag('ul');
2400 } else {
2401 echo $OUTPUT->heading(get_string("nocoursesyet"));
2402 $context = get_context_instance(CONTEXT_SYSTEM);
2403 if (has_capability('moodle/course:create', $context)) {
2404 $options = array();
2405 if (!empty($category->id)) {
2406 $options['category'] = $category->id;
2407 } else {
2408 $options['category'] = $CFG->defaultrequestcategory;
2410 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2411 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2412 echo html_writer::end_tag('div');
2418 * Print a description of a course, suitable for browsing in a list.
2420 * @param object $course the course object.
2421 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2423 function print_course($course, $highlightterms = '') {
2424 global $CFG, $USER, $DB, $OUTPUT;
2426 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2428 // Rewrite file URLs so that they are correct
2429 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2431 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2432 echo html_writer::start_tag('div', array('class'=>'info'));
2433 echo html_writer::start_tag('h3', array('class'=>'name'));
2435 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2437 $coursename = get_course_display_name_for_list($course);
2438 $linktext = highlight($highlightterms, format_string($coursename));
2439 $linkparams = array('title'=>get_string('entercourse'));
2440 if (empty($course->visible)) {
2441 $linkparams['class'] = 'dimmed';
2443 echo html_writer::link($linkhref, $linktext, $linkparams);
2444 echo html_writer::end_tag('h3');
2446 /// first find all roles that are supposed to be displayed
2447 if (!empty($CFG->coursecontact)) {
2448 $managerroles = explode(',', $CFG->coursecontact);
2449 $namesarray = array();
2450 $rusers = array();
2452 if (!isset($course->managers)) {
2453 $rusers = get_role_users($managerroles, $context, true,
2454 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2455 r.name AS rolename, r.sortorder, r.id AS roleid',
2456 'r.sortorder ASC, u.lastname ASC');
2457 } else {
2458 // use the managers array if we have it for perf reasosn
2459 // populate the datastructure like output of get_role_users();
2460 foreach ($course->managers as $manager) {
2461 $u = new stdClass();
2462 $u = $manager->user;
2463 $u->roleid = $manager->roleid;
2464 $u->rolename = $manager->rolename;
2466 $rusers[] = $u;
2470 /// Rename some of the role names if needed
2471 if (isset($context)) {
2472 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2475 $namesarray = array();
2476 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2477 foreach ($rusers as $ra) {
2478 if (isset($namesarray[$ra->id])) {
2479 // only display a user once with the higest sortorder role
2480 continue;
2483 if (isset($aliasnames[$ra->roleid])) {
2484 $ra->rolename = $aliasnames[$ra->roleid]->name;
2487 $fullname = fullname($ra, $canviewfullnames);
2488 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2489 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2492 if (!empty($namesarray)) {
2493 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2494 foreach ($namesarray as $name) {
2495 echo html_writer::tag('li', $name);
2497 echo html_writer::end_tag('ul');
2500 echo html_writer::end_tag('div'); // End of info div
2502 echo html_writer::start_tag('div', array('class'=>'summary'));
2503 $options = new stdClass();
2504 $options->noclean = true;
2505 $options->para = false;
2506 $options->overflowdiv = true;
2507 if (!isset($course->summaryformat)) {
2508 $course->summaryformat = FORMAT_MOODLE;
2510 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2511 if ($icons = enrol_get_course_info_icons($course)) {
2512 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2513 foreach ($icons as $icon) {
2514 echo $OUTPUT->render($icon);
2516 echo html_writer::end_tag('div'); // End of enrolmenticons div
2518 echo html_writer::end_tag('div'); // End of summary div
2519 echo html_writer::end_tag('div'); // End of coursebox div
2523 * Prints custom user information on the home page.
2524 * Over time this can include all sorts of information
2526 function print_my_moodle() {
2527 global $USER, $CFG, $DB, $OUTPUT;
2529 if (!isloggedin() or isguestuser()) {
2530 print_error('nopermissions', '', '', 'See My Moodle');
2533 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2534 $rhosts = array();
2535 $rcourses = array();
2536 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2537 $rcourses = get_my_remotecourses($USER->id);
2538 $rhosts = get_my_remotehosts();
2541 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2543 if (!empty($courses)) {
2544 echo '<ul class="unlist">';
2545 foreach ($courses as $course) {
2546 if ($course->id == SITEID) {
2547 continue;
2549 echo '<li>';
2550 print_course($course);
2551 echo "</li>\n";
2553 echo "</ul>\n";
2556 // MNET
2557 if (!empty($rcourses)) {
2558 // at the IDP, we know of all the remote courses
2559 foreach ($rcourses as $course) {
2560 print_remote_course($course, "100%");
2562 } elseif (!empty($rhosts)) {
2563 // non-IDP, we know of all the remote servers, but not courses
2564 foreach ($rhosts as $host) {
2565 print_remote_host($host, "100%");
2568 unset($course);
2569 unset($host);
2571 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2572 echo "<table width=\"100%\"><tr><td align=\"center\">";
2573 print_course_search("", false, "short");
2574 echo "</td><td align=\"center\">";
2575 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2576 echo "</td></tr></table>\n";
2579 } else {
2580 if ($DB->count_records("course_categories") > 1) {
2581 echo $OUTPUT->box_start("categorybox");
2582 print_whole_category_list();
2583 echo $OUTPUT->box_end();
2584 } else {
2585 print_courses(0);
2591 function print_course_search($value="", $return=false, $format="plain") {
2592 global $CFG;
2593 static $count = 0;
2595 $count++;
2597 $id = 'coursesearch';
2599 if ($count > 1) {
2600 $id .= $count;
2603 $strsearchcourses= get_string("searchcourses");
2605 if ($format == 'plain') {
2606 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2607 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2608 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2609 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2610 $output .= '<input type="submit" value="'.get_string('go').'" />';
2611 $output .= '</fieldset></form>';
2612 } else if ($format == 'short') {
2613 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2614 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2615 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2616 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2617 $output .= '<input type="submit" value="'.get_string('go').'" />';
2618 $output .= '</fieldset></form>';
2619 } else if ($format == 'navbar') {
2620 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2621 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2622 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2623 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2624 $output .= '<input type="submit" value="'.get_string('go').'" />';
2625 $output .= '</fieldset></form>';
2628 if ($return) {
2629 return $output;
2631 echo $output;
2634 function print_remote_course($course, $width="100%") {
2635 global $CFG, $USER;
2637 $linkcss = '';
2639 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2641 echo '<div class="coursebox remotecoursebox clearfix">';
2642 echo '<div class="info">';
2643 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2644 $linkcss.' href="'.$url.'">'
2645 . format_string($course->fullname) .'</a><br />'
2646 . format_string($course->hostname) . ' : '
2647 . format_string($course->cat_name) . ' : '
2648 . format_string($course->shortname). '</div>';
2649 echo '</div><div class="summary">';
2650 $options = new stdClass();
2651 $options->noclean = true;
2652 $options->para = false;
2653 $options->overflowdiv = true;
2654 echo format_text($course->summary, $course->summaryformat, $options);
2655 echo '</div>';
2656 echo '</div>';
2659 function print_remote_host($host, $width="100%") {
2660 global $OUTPUT;
2662 $linkcss = '';
2664 echo '<div class="coursebox clearfix">';
2665 echo '<div class="info">';
2666 echo '<div class="name">';
2667 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2668 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2669 . s($host['name']).'</a> - ';
2670 echo $host['count'] . ' ' . get_string('courses');
2671 echo '</div>';
2672 echo '</div>';
2673 echo '</div>';
2677 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2679 function add_course_module($mod) {
2680 global $DB;
2682 $mod->added = time();
2683 unset($mod->id);
2685 return $DB->insert_record("course_modules", $mod);
2689 * Returns course section - creates new if does not exist yet.
2690 * @param int $relative section number
2691 * @param int $courseid
2692 * @return object $course_section object
2694 function get_course_section($section, $courseid) {
2695 global $DB;
2697 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2698 return $cw;
2700 $cw = new stdClass();
2701 $cw->course = $courseid;
2702 $cw->section = $section;
2703 $cw->summary = "";
2704 $cw->summaryformat = FORMAT_HTML;
2705 $cw->sequence = "";
2706 $id = $DB->insert_record("course_sections", $cw);
2707 return $DB->get_record("course_sections", array("id"=>$id));
2710 * Given a full mod object with section and course already defined, adds this module to that section.
2712 * @param object $mod
2713 * @param int $beforemod An existing ID which we will insert the new module before
2714 * @return int The course_sections ID where the mod is inserted
2716 function add_mod_to_section($mod, $beforemod=NULL) {
2717 global $DB;
2719 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2721 $section->sequence = trim($section->sequence);
2723 if (empty($section->sequence)) {
2724 $newsequence = "$mod->coursemodule";
2726 } else if ($beforemod) {
2727 $modarray = explode(",", $section->sequence);
2729 if ($key = array_keys($modarray, $beforemod->id)) {
2730 $insertarray = array($mod->id, $beforemod->id);
2731 array_splice($modarray, $key[0], 1, $insertarray);
2732 $newsequence = implode(",", $modarray);
2734 } else { // Just tack it on the end anyway
2735 $newsequence = "$section->sequence,$mod->coursemodule";
2738 } else {
2739 $newsequence = "$section->sequence,$mod->coursemodule";
2742 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2743 return $section->id; // Return course_sections ID that was used.
2745 } else { // Insert a new record
2746 $section->course = $mod->course;
2747 $section->section = $mod->section;
2748 $section->summary = "";
2749 $section->summaryformat = FORMAT_HTML;
2750 $section->sequence = $mod->coursemodule;
2751 return $DB->insert_record("course_sections", $section);
2755 function set_coursemodule_groupmode($id, $groupmode) {
2756 global $DB;
2757 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2760 function set_coursemodule_idnumber($id, $idnumber) {
2761 global $DB;
2762 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2766 * $prevstateoverrides = true will set the visibility of the course module
2767 * to what is defined in visibleold. This enables us to remember the current
2768 * visibility when making a whole section hidden, so that when we toggle
2769 * that section back to visible, we are able to return the visibility of
2770 * the course module back to what it was originally.
2772 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2773 global $DB, $CFG;
2774 require_once($CFG->libdir.'/gradelib.php');
2776 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2777 return false;
2779 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2780 return false;
2782 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2783 foreach($events as $event) {
2784 if ($visible) {
2785 show_event($event);
2786 } else {
2787 hide_event($event);
2792 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2793 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2794 if ($grade_items) {
2795 foreach ($grade_items as $grade_item) {
2796 $grade_item->set_hidden(!$visible);
2800 if ($prevstateoverrides) {
2801 if ($visible == '0') {
2802 // Remember the current visible state so we can toggle this back.
2803 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2804 } else {
2805 // Get the previous saved visible states.
2806 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2809 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2813 * Delete a course module and any associated data at the course level (events)
2814 * Until 1.5 this function simply marked a deleted flag ... now it
2815 * deletes it completely.
2818 function delete_course_module($id) {
2819 global $CFG, $DB;
2820 require_once($CFG->libdir.'/gradelib.php');
2821 require_once($CFG->dirroot.'/blog/lib.php');
2823 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2824 return true;
2826 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2827 //delete events from calendar
2828 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2829 foreach($events as $event) {
2830 delete_event($event->id);
2833 //delete grade items, outcome items and grades attached to modules
2834 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2835 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2836 foreach ($grade_items as $grade_item) {
2837 $grade_item->delete('moddelete');
2840 // Delete completion and availability data; it is better to do this even if the
2841 // features are not turned on, in case they were turned on previously (these will be
2842 // very quick on an empty table)
2843 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2844 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2845 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2846 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2848 delete_context(CONTEXT_MODULE, $cm->id);
2849 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2852 function delete_mod_from_section($mod, $section) {
2853 global $DB;
2855 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2857 $modarray = explode(",", $section->sequence);
2859 if ($key = array_keys ($modarray, $mod)) {
2860 array_splice($modarray, $key[0], 1);
2861 $newsequence = implode(",", $modarray);
2862 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2863 } else {
2864 return false;
2868 return false;
2872 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2874 * @param object $course course object
2875 * @param int $section Section number (not id!!!)
2876 * @param int $move (-1 or 1)
2877 * @return boolean true if section moved successfully
2879 function move_section($course, $section, $move) {
2880 /// Moves a whole course section up and down within the course
2881 global $USER, $DB;
2883 if (!$move) {
2884 return true;
2887 $sectiondest = $section + $move;
2889 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2890 return false;
2893 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2894 return false;
2897 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2898 return false;
2901 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2902 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2904 // Update highlighting if the move affects highlighted section
2905 if ($course->marker == $section) {
2906 course_set_marker($course->id, $sectiondest);
2907 } elseif ($course->marker == $sectiondest) {
2908 course_set_marker($course->id, $section);
2911 // if the focus is on the section that is being moved, then move the focus along
2912 if (course_get_display($course->id) == $section) {
2913 course_set_display($course->id, $sectiondest);
2916 // Check for duplicates and fix order if needed.
2917 // There is a very rare case that some sections in the same course have the same section id.
2918 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2919 $n = 0;
2920 foreach ($sections as $section) {
2921 if ($section->section != $n) {
2922 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
2924 $n++;
2926 return true;
2930 * Moves a section within a course, from a position to another.
2931 * Be very careful: $section and $destination refer to section number,
2932 * not id!.
2934 * @param object $course
2935 * @param int $section Section number (not id!!!)
2936 * @param int $destination
2937 * @return boolean Result
2939 function move_section_to($course, $section, $destination) {
2940 /// Moves a whole course section up and down within the course
2941 global $USER, $DB;
2943 if (!$destination && $destination != 0) {
2944 return true;
2947 if ($destination > $course->numsections) {
2948 return false;
2951 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2952 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2953 'section ASC, id ASC', 'id, section')) {
2954 return false;
2957 $sections = reorder_sections($sections, $section, $destination);
2959 // Update all sections
2960 foreach ($sections as $id => $position) {
2961 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2964 // if the focus is on the section that is being moved, then move the focus along
2965 if (course_get_display($course->id) == $section) {
2966 course_set_display($course->id, $destination);
2968 return true;
2972 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2973 * an original position number and a target position number, rebuilds the array so that the
2974 * move is made without any duplication of section positions.
2975 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2976 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2978 * @param array $sections
2979 * @param int $origin_position
2980 * @param int $target_position
2981 * @return array
2983 function reorder_sections($sections, $origin_position, $target_position) {
2984 if (!is_array($sections)) {
2985 return false;
2988 // We can't move section position 0
2989 if ($origin_position < 1) {
2990 echo "We can't move section position 0";
2991 return false;
2994 // Locate origin section in sections array
2995 if (!$origin_key = array_search($origin_position, $sections)) {
2996 echo "searched position not in sections array";
2997 return false; // searched position not in sections array
3000 // Extract origin section
3001 $origin_section = $sections[$origin_key];
3002 unset($sections[$origin_key]);
3004 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3005 $found = false;
3006 $append_array = array();
3007 foreach ($sections as $id => $position) {
3008 if ($found) {
3009 $append_array[$id] = $position;
3010 unset($sections[$id]);
3012 if ($position == $target_position) {
3013 $found = true;
3017 // Append moved section
3018 $sections[$origin_key] = $origin_section;
3020 // Append rest of array (if applicable)
3021 if (!empty($append_array)) {
3022 foreach ($append_array as $id => $position) {
3023 $sections[$id] = $position;
3027 // Renumber positions
3028 $position = 0;
3029 foreach ($sections as $id => $p) {
3030 $sections[$id] = $position;
3031 $position++;
3034 return $sections;
3039 * Move the module object $mod to the specified $section
3040 * If $beforemod exists then that is the module
3041 * before which $modid should be inserted
3042 * All parameters are objects
3044 function moveto_module($mod, $section, $beforemod=NULL) {
3045 global $DB, $OUTPUT;
3047 /// Remove original module from original section
3048 if (! delete_mod_from_section($mod->id, $mod->section)) {
3049 echo $OUTPUT->notification("Could not delete module from existing section");
3052 /// Update module itself if necessary
3054 if ($mod->section != $section->id) {
3055 $mod->section = $section->id;
3056 $DB->update_record("course_modules", $mod);
3057 // if moving to a hidden section then hide module
3058 if (!$section->visible) {
3059 set_coursemodule_visible($mod->id, 0);
3063 /// Add the module into the new section
3065 $mod->course = $section->course;
3066 $mod->section = $section->section; // need relative reference
3067 $mod->coursemodule = $mod->id;
3069 if (! add_mod_to_section($mod, $beforemod)) {
3070 return false;
3073 return true;
3077 * Produces the editing buttons for a module
3079 * @global core_renderer $OUTPUT
3080 * @staticvar type $str
3081 * @param stdClass $mod The module to produce editing buttons for
3082 * @param bool $absolute_ignored ignored - all links are absolute
3083 * @param bool $moveselect If true a move seleciton process is used (default true)
3084 * @param int $indent The current indenting
3085 * @param int $section The section to link back to
3086 * @return string XHTML for the editing buttons
3088 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3089 global $CFG, $OUTPUT;
3091 static $str;
3093 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3094 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3096 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3097 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3099 // no permission to edit anything
3100 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3101 return false;
3104 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3106 if (!isset($str)) {
3107 $str = new stdClass;
3108 $str->assign = get_string("assignroles", 'role');
3109 $str->delete = get_string("delete");
3110 $str->move = get_string("move");
3111 $str->moveup = get_string("moveup");
3112 $str->movedown = get_string("movedown");
3113 $str->moveright = get_string("moveright");
3114 $str->moveleft = get_string("moveleft");
3115 $str->update = get_string("update");
3116 $str->duplicate = get_string("duplicate");
3117 $str->hide = get_string("hide");
3118 $str->show = get_string("show");
3119 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3120 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3121 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3122 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3123 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3124 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3127 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3129 if ($section >= 0) {
3130 $baseurl->param('sr', $section);
3132 $actions = array();
3134 // leftright
3135 if ($hasmanageactivities) {
3136 if (right_to_left()) { // Exchange arrows on RTL
3137 $rightarrow = 't/left';
3138 $leftarrow = 't/right';
3139 } else {
3140 $rightarrow = 't/right';
3141 $leftarrow = 't/left';
3144 if ($indent > 0) {
3145 $actions[] = new action_link(
3146 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3147 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3148 null,
3149 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3152 if ($indent >= 0) {
3153 $actions[] = new action_link(
3154 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3155 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3156 null,
3157 array('class' => 'editing_moveright', 'title' => $str->moveright)
3162 // move
3163 if ($hasmanageactivities) {
3164 if ($moveselect) {
3165 $actions[] = new action_link(
3166 new moodle_url($baseurl, array('copy' => $mod->id)),
3167 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3168 null,
3169 array('class' => 'editing_move', 'title' => $str->move)
3171 } else {
3172 $actions[] = new action_link(
3173 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3174 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3175 null,
3176 array('class' => 'editing_moveup', 'title' => $str->moveup)
3178 $actions[] = new action_link(
3179 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3180 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3181 null,
3182 array('class' => 'editing_movedown', 'title' => $str->movedown)
3187 // Update
3188 if ($hasmanageactivities) {
3189 $actions[] = new action_link(
3190 new moodle_url($baseurl, array('update' => $mod->id)),
3191 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3192 null,
3193 array('class' => 'editing_update', 'title' => $str->update)
3197 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3198 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3199 $actions[] = new action_link(
3200 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3201 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3202 null,
3203 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3207 // Delete
3208 if ($hasmanageactivities) {
3209 $actions[] = new action_link(
3210 new moodle_url($baseurl, array('delete' => $mod->id)),
3211 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3212 null,
3213 array('class' => 'editing_delete', 'title' => $str->delete)
3217 // hideshow
3218 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3219 if ($mod->visible) {
3220 $actions[] = new action_link(
3221 new moodle_url($baseurl, array('hide' => $mod->id)),
3222 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3223 null,
3224 array('class' => 'editing_hide', 'title' => $str->hide)
3226 } else {
3227 $actions[] = new action_link(
3228 new moodle_url($baseurl, array('show' => $mod->id)),
3229 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3230 null,
3231 array('class' => 'editing_show', 'title' => $str->show)
3236 // groupmode
3237 if ($hasmanageactivities and $mod->groupmode !== false) {
3238 if ($mod->groupmode == SEPARATEGROUPS) {
3239 $groupmode = 0;
3240 $grouptitle = $str->groupsseparate;
3241 $forcedgrouptitle = $str->forcedgroupsseparate;
3242 $groupclass = 'editing_groupsseparate';
3243 $groupimage = 't/groups';
3244 } else if ($mod->groupmode == VISIBLEGROUPS) {
3245 $groupmode = 1;
3246 $grouptitle = $str->groupsvisible;
3247 $forcedgrouptitle = $str->forcedgroupsvisible;
3248 $groupclass = 'editing_groupsvisible';
3249 $groupimage = 't/groupv';
3250 } else {
3251 $groupmode = 2;
3252 $grouptitle = $str->groupsnone;
3253 $forcedgrouptitle = $str->forcedgroupsnone;
3254 $groupclass = 'editing_groupsnone';
3255 $groupimage = 't/groupn';
3257 if ($mod->groupmodelink) {
3258 $actions[] = new action_link(
3259 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3260 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3261 null,
3262 array('class' => $groupclass, 'title' => $grouptitle)
3264 } else {
3265 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3269 // Assign
3270 if (has_capability('moodle/role:assign', $modcontext)){
3271 $actions[] = new action_link(
3272 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3273 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
3274 null,
3275 array('class' => 'editing_assign', 'title' => $str->assign)
3279 $output = html_writer::start_tag('span', array('class' => 'commands'));
3280 foreach ($actions as $action) {
3281 if ($action instanceof renderable) {
3282 $output .= $OUTPUT->render($action);
3283 } else {
3284 $output .= $action;
3287 $output .= html_writer::end_tag('span');
3288 return $output;
3292 * given a course object with shortname & fullname, this function will
3293 * truncate the the number of chars allowed and add ... if it was too long
3295 function course_format_name ($course,$max=100) {
3297 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3298 $shortname = format_string($course->shortname, true, array('context' => $context));
3299 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3300 $str = $shortname.': '. $fullname;
3301 if (textlib::strlen($str) <= $max) {
3302 return $str;
3304 else {
3305 return textlib::substr($str,0,$max-3).'...';
3309 function update_restricted_mods($course, $mods) {
3310 global $DB;
3312 /// Delete all the current restricted list
3313 $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
3315 if (empty($course->restrictmodules)) {
3316 return; // We're done
3319 /// Insert the new list of restricted mods
3320 foreach ($mods as $mod) {
3321 if ($mod == 0) {
3322 continue; // this is the 'allow none' option
3324 $am = new stdClass();
3325 $am->course = $course->id;
3326 $am->module = $mod;
3327 $DB->insert_record('course_allowed_modules',$am);
3332 * This function will take an int (module id) or a string (module name)
3333 * and return true or false, whether it's allowed in the given course (object)
3334 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3335 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3338 function course_allowed_module($course,$mod) {
3339 global $DB;
3341 if (empty($course->restrictmodules)) {
3342 return true;
3345 // Admins and admin-like people who can edit everything can also add anything.
3346 // Originally there was a course:update test only, but it did not match the test in course edit form
3347 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3348 return true;
3351 if (is_numeric($mod)) {
3352 $modid = $mod;
3353 } else if (is_string($mod)) {
3354 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3356 if (empty($modid)) {
3357 return false;
3360 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
3364 * Recursively delete category including all subcategories and courses.
3365 * @param stdClass $category
3366 * @param boolean $showfeedback display some notices
3367 * @return array return deleted courses
3369 function category_delete_full($category, $showfeedback=true) {
3370 global $CFG, $DB;
3371 require_once($CFG->libdir.'/gradelib.php');
3372 require_once($CFG->libdir.'/questionlib.php');
3373 require_once($CFG->dirroot.'/cohort/lib.php');
3375 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3376 foreach ($children as $childcat) {
3377 category_delete_full($childcat, $showfeedback);
3381 $deletedcourses = array();
3382 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3383 foreach ($courses as $course) {
3384 if (!delete_course($course, false)) {
3385 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3387 $deletedcourses[] = $course;
3391 // move or delete cohorts in this context
3392 cohort_delete_category($category);
3394 // now delete anything that may depend on course category context
3395 grade_course_category_delete($category->id, 0, $showfeedback);
3396 if (!question_delete_course_category($category, 0, $showfeedback)) {
3397 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3400 // finally delete the category and it's context
3401 $DB->delete_records('course_categories', array('id'=>$category->id));
3402 delete_context(CONTEXT_COURSECAT, $category->id);
3404 events_trigger('course_category_deleted', $category);
3406 return $deletedcourses;
3410 * Delete category, but move contents to another category.
3411 * @param object $ccategory
3412 * @param int $newparentid category id
3413 * @return bool status
3415 function category_delete_move($category, $newparentid, $showfeedback=true) {
3416 global $CFG, $DB, $OUTPUT;
3417 require_once($CFG->libdir.'/gradelib.php');
3418 require_once($CFG->libdir.'/questionlib.php');
3419 require_once($CFG->dirroot.'/cohort/lib.php');
3421 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3422 return false;
3425 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3426 foreach ($children as $childcat) {
3427 move_category($childcat, $newparentcat);
3431 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3432 if (!move_courses(array_keys($courses), $newparentid)) {
3433 echo $OUTPUT->notification("Error moving courses");
3434 return false;
3436 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3439 // move or delete cohorts in this context
3440 cohort_delete_category($category);
3442 // now delete anything that may depend on course category context
3443 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3444 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3445 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3446 return false;
3449 // finally delete the category and it's context
3450 $DB->delete_records('course_categories', array('id'=>$category->id));
3451 delete_context(CONTEXT_COURSECAT, $category->id);
3453 events_trigger('course_category_deleted', $category);
3455 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3457 return true;
3461 * Efficiently moves many courses around while maintaining
3462 * sortorder in order.
3464 * @param array $courseids is an array of course ids
3465 * @param int $categoryid
3466 * @return bool success
3468 function move_courses($courseids, $categoryid) {
3469 global $CFG, $DB, $OUTPUT;
3471 if (empty($courseids)) {
3472 // nothing to do
3473 return;
3476 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3477 return false;
3480 $courseids = array_reverse($courseids);
3481 $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3482 $i = 1;
3484 foreach ($courseids as $courseid) {
3485 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3486 $course = new stdClass();
3487 $course->id = $courseid;
3488 $course->category = $category->id;
3489 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3490 if ($category->visible == 0) {
3491 // hide the course when moving into hidden category,
3492 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3493 $course->visible = 0;
3496 $DB->update_record('course', $course);
3498 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3499 context_moved($context, $newparent);
3502 fix_course_sortorder();
3504 return true;
3508 * Hide course category and child course and subcategories
3509 * @param stdClass $category
3510 * @return void
3512 function course_category_hide($category) {
3513 global $DB;
3515 $category->visible = 0;
3516 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3517 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3518 $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
3519 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3520 // get all child categories and hide too
3521 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3522 foreach ($subcats as $cat) {
3523 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3524 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3525 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3526 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3532 * Show course category and child course and subcategories
3533 * @param stdClass $category
3534 * @return void
3536 function course_category_show($category) {
3537 global $DB;
3539 $category->visible = 1;
3540 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3541 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3542 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3543 // get all child categories and unhide too
3544 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3545 foreach ($subcats as $cat) {
3546 if ($cat->visibleold) {
3547 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3549 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3555 * Efficiently moves a category - NOTE that this can have
3556 * a huge impact access-control-wise...
3558 function move_category($category, $newparentcat) {
3559 global $CFG, $DB;
3561 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3563 $hidecat = false;
3564 if (empty($newparentcat->id)) {
3565 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3567 $newparent = get_context_instance(CONTEXT_SYSTEM);
3569 } else {
3570 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3571 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3573 if (!$newparentcat->visible and $category->visible) {
3574 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3575 $hidecat = true;
3579 context_moved($context, $newparent);
3581 // now make it last in new category
3582 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3584 // and fix the sortorders
3585 fix_course_sortorder();
3587 if ($hidecat) {
3588 course_category_hide($category);
3593 * Returns the display name of the given section that the course prefers.
3595 * This function utilizes a callback that can be implemented within the course
3596 * formats lib.php file to customize the display name that is used to reference
3597 * the section.
3599 * By default (if callback is not defined) the method
3600 * {@see get_numeric_section_name} is called instead.
3602 * @param stdClass $course The course to get the section name for
3603 * @param stdClass $section Section object from database
3604 * @return Display name that the course format prefers, e.g. "Week 2"
3606 * @see get_generic_section_name
3608 function get_section_name(stdClass $course, stdClass $section) {
3609 global $CFG;
3611 /// Inelegant hack for bug 3408
3612 if ($course->format == 'site') {
3613 return get_string('site');
3616 // Use course formatter callback if it exists
3617 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3618 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3619 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3620 require_once $namingfile;
3622 if (function_exists($namingfunction)) {
3623 return $namingfunction($course, $section);
3626 // else, default behavior:
3627 return get_generic_section_name($course->format, $section);
3631 * Gets the generic section name for a courses section.
3633 * @param string $format Course format ID e.g. 'weeks' $course->format
3634 * @param stdClass $section Section object from database
3635 * @return Display name that the course format prefers, e.g. "Week 2"
3637 function get_generic_section_name($format, stdClass $section) {
3638 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3642 function course_format_uses_sections($format) {
3643 global $CFG;
3645 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3646 $featurefunction = 'callback_'.$format.'_uses_sections';
3647 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3648 require_once $featurefile;
3650 if (function_exists($featurefunction)) {
3651 return $featurefunction();
3654 return false;
3658 * Returns the information about the ajax support in the given source format
3660 * The returned object's property (boolean)capable indicates that
3661 * the course format supports Moodle course ajax features.
3662 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3664 * @param string $format
3665 * @return stdClass
3667 function course_format_ajax_support($format) {
3668 global $CFG;
3670 // set up default values
3671 $ajaxsupport = new stdClass();
3672 $ajaxsupport->capable = false;
3673 $ajaxsupport->testedbrowsers = array();
3675 // get the information from the course format library
3676 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3677 $featurefunction = 'callback_'.$format.'_ajax_support';
3678 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3679 require_once $featurefile;
3681 if (function_exists($featurefunction)) {
3682 $formatsupport = $featurefunction();
3683 if (isset($formatsupport->capable)) {
3684 $ajaxsupport->capable = $formatsupport->capable;
3686 if (is_array($formatsupport->testedbrowsers)) {
3687 $ajaxsupport->testedbrowsers = $formatsupport->testedbrowsers;
3691 return $ajaxsupport;
3695 * Can the current user delete this course?
3696 * Course creators have exception,
3697 * 1 day after the creation they can sill delete the course.
3698 * @param int $courseid
3699 * @return boolean
3701 function can_delete_course($courseid) {
3702 global $USER, $DB;
3704 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3706 if (has_capability('moodle/course:delete', $context)) {
3707 return true;
3710 // hack: now try to find out if creator created this course recently (1 day)
3711 if (!has_capability('moodle/course:create', $context)) {
3712 return false;
3715 $since = time() - 60*60*24;
3717 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3718 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3720 return $DB->record_exists_select('log', $select, $params);
3724 * Save the Your name for 'Some role' strings.
3726 * @param integer $courseid the id of this course.
3727 * @param array $data the data that came from the course settings form.
3729 function save_local_role_names($courseid, $data) {
3730 global $DB;
3731 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3733 foreach ($data as $fieldname => $value) {
3734 if (strpos($fieldname, 'role_') !== 0) {
3735 continue;
3737 list($ignored, $roleid) = explode('_', $fieldname);
3739 // make up our mind whether we want to delete, update or insert
3740 if (!$value) {
3741 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3743 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3744 $rolename->name = $value;
3745 $DB->update_record('role_names', $rolename);
3747 } else {
3748 $rolename = new stdClass;
3749 $rolename->contextid = $context->id;
3750 $rolename->roleid = $roleid;
3751 $rolename->name = $value;
3752 $DB->insert_record('role_names', $rolename);
3758 * Create a course and either return a $course object
3760 * Please note this functions does not verify any access control,
3761 * the calling code is responsible for all validation (usually it is the form definition).
3763 * @param array $editoroptions course description editor options
3764 * @param object $data - all the data needed for an entry in the 'course' table
3765 * @return object new course instance
3767 function create_course($data, $editoroptions = NULL) {
3768 global $CFG, $DB;
3770 //check the categoryid - must be given for all new courses
3771 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3773 //check if the shortname already exist
3774 if (!empty($data->shortname)) {
3775 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3776 throw new moodle_exception('shortnametaken');
3780 //check if the id number already exist
3781 if (!empty($data->idnumber)) {
3782 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3783 throw new moodle_exception('idnumbertaken');
3787 $data->timecreated = time();
3788 $data->timemodified = $data->timecreated;
3790 // place at beginning of any category
3791 $data->sortorder = 0;
3793 if ($editoroptions) {
3794 // summary text is updated later, we need context to store the files first
3795 $data->summary = '';
3796 $data->summary_format = FORMAT_HTML;
3799 if (!isset($data->visible)) {
3800 // data not from form, add missing visibility info
3801 $data->visible = $category->visible;
3803 $data->visibleold = $data->visible;
3805 $newcourseid = $DB->insert_record('course', $data);
3806 $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
3808 if ($editoroptions) {
3809 // Save the files used in the summary editor and store
3810 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3811 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3812 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3815 $course = $DB->get_record('course', array('id'=>$newcourseid));
3817 // Setup the blocks
3818 blocks_add_default_course_blocks($course);
3820 $section = new stdClass();
3821 $section->course = $course->id; // Create a default section.
3822 $section->section = 0;
3823 $section->summaryformat = FORMAT_HTML;
3824 $DB->insert_record('course_sections', $section);
3826 fix_course_sortorder();
3828 // update module restrictions
3829 if ($course->restrictmodules || $CFG->restrictbydefault ) {
3830 if (isset($data->allowedmods)) {
3831 update_restricted_mods($course, $data->allowedmods);
3832 } else {
3833 if (!empty($CFG->defaultallowedmodules)) {
3834 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
3839 // new context created - better mark it as dirty
3840 mark_context_dirty($context->path);
3842 // Save any custom role names.
3843 save_local_role_names($course->id, (array)$data);
3845 // set up enrolments
3846 enrol_course_updated(true, $course, $data);
3848 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3850 // Trigger events
3851 events_trigger('course_created', $course);
3853 return $course;
3857 * Update a course.
3859 * Please note this functions does not verify any access control,
3860 * the calling code is responsible for all validation (usually it is the form definition).
3862 * @param object $data - all the data needed for an entry in the 'course' table
3863 * @param array $editoroptions course description editor options
3864 * @return void
3866 function update_course($data, $editoroptions = NULL) {
3867 global $CFG, $DB;
3869 $data->timemodified = time();
3871 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
3872 $context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
3874 if ($editoroptions) {
3875 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3878 if (!isset($data->category) or empty($data->category)) {
3879 // prevent nulls and 0 in category field
3880 unset($data->category);
3882 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3884 if (!isset($data->visible)) {
3885 // data not from form, add missing visibility info
3886 $data->visible = $oldcourse->visible;
3889 if ($data->visible != $oldcourse->visible) {
3890 // reset the visibleold flag when manually hiding/unhiding course
3891 $data->visibleold = $data->visible;
3892 } else {
3893 if ($movecat) {
3894 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3895 if (empty($newcategory->visible)) {
3896 // make sure when moving into hidden category the course is hidden automatically
3897 $data->visible = 0;
3902 // Update with the new data
3903 $DB->update_record('course', $data);
3905 $course = $DB->get_record('course', array('id'=>$data->id));
3907 if ($movecat) {
3908 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3909 context_moved($context, $newparent);
3912 fix_course_sortorder();
3914 // Test for and remove blocks which aren't appropriate anymore
3915 blocks_remove_inappropriate($course);
3917 // update module restrictions
3918 if (isset($data->allowedmods)) {
3919 update_restricted_mods($course, $data->allowedmods);
3922 // Save any custom role names.
3923 save_local_role_names($course->id, $data);
3925 // update enrol settings
3926 enrol_course_updated(false, $course, $data);
3928 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3930 // Trigger events
3931 events_trigger('course_updated', $course);
3935 * Average number of participants
3936 * @return integer
3938 function average_number_of_participants() {
3939 global $DB, $SITE;
3941 //count total of enrolments for visible course (except front page)
3942 $sql = 'SELECT COUNT(*) FROM (
3943 SELECT DISTINCT ue.userid, e.courseid
3944 FROM {user_enrolments} ue, {enrol} e, {course} c
3945 WHERE ue.enrolid = e.id
3946 AND e.courseid <> :siteid
3947 AND c.id = e.courseid
3948 AND c.visible = 1) total';
3949 $params = array('siteid' => $SITE->id);
3950 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3953 //count total of visible courses (minus front page)
3954 $coursetotal = $DB->count_records('course', array('visible' => 1));
3955 $coursetotal = $coursetotal - 1 ;
3957 //average of enrolment
3958 if (empty($coursetotal)) {
3959 $participantaverage = 0;
3960 } else {
3961 $participantaverage = $enrolmenttotal / $coursetotal;
3964 return $participantaverage;
3968 * Average number of course modules
3969 * @return integer
3971 function average_number_of_courses_modules() {
3972 global $DB, $SITE;
3974 //count total of visible course module (except front page)
3975 $sql = 'SELECT COUNT(*) FROM (
3976 SELECT cm.course, cm.module
3977 FROM {course} c, {course_modules} cm
3978 WHERE c.id = cm.course
3979 AND c.id <> :siteid
3980 AND cm.visible = 1
3981 AND c.visible = 1) total';
3982 $params = array('siteid' => $SITE->id);
3983 $moduletotal = $DB->count_records_sql($sql, $params);
3986 //count total of visible courses (minus front page)
3987 $coursetotal = $DB->count_records('course', array('visible' => 1));
3988 $coursetotal = $coursetotal - 1 ;
3990 //average of course module
3991 if (empty($coursetotal)) {
3992 $coursemoduleaverage = 0;
3993 } else {
3994 $coursemoduleaverage = $moduletotal / $coursetotal;
3997 return $coursemoduleaverage;
4001 * This class pertains to course requests and contains methods associated with
4002 * create, approving, and removing course requests.
4004 * Please note we do not allow embedded images here because there is no context
4005 * to store them with proper access control.
4007 * @copyright 2009 Sam Hemelryk
4008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4009 * @since Moodle 2.0
4011 * @property-read int $id
4012 * @property-read string $fullname
4013 * @property-read string $shortname
4014 * @property-read string $summary
4015 * @property-read int $summaryformat
4016 * @property-read int $summarytrust
4017 * @property-read string $reason
4018 * @property-read int $requester
4020 class course_request {
4023 * This is the stdClass that stores the properties for the course request
4024 * and is externally accessed through the __get magic method
4025 * @var stdClass
4027 protected $properties;
4030 * An array of options for the summary editor used by course request forms.
4031 * This is initially set by {@link summary_editor_options()}
4032 * @var array
4033 * @static
4035 protected static $summaryeditoroptions;
4038 * Static function to prepare the summary editor for working with a course
4039 * request.
4041 * @static
4042 * @param null|stdClass $data Optional, an object containing the default values
4043 * for the form, these may be modified when preparing the
4044 * editor so this should be called before creating the form
4045 * @return stdClass An object that can be used to set the default values for
4046 * an mforms form
4048 public static function prepare($data=null) {
4049 if ($data === null) {
4050 $data = new stdClass;
4052 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4053 return $data;
4057 * Static function to create a new course request when passed an array of properties
4058 * for it.
4060 * This function also handles saving any files that may have been used in the editor
4062 * @static
4063 * @param stdClass $data
4064 * @return course_request The newly created course request
4066 public static function create($data) {
4067 global $USER, $DB, $CFG;
4068 $data->requester = $USER->id;
4070 // Summary is a required field so copy the text over
4071 $data->summary = $data->summary_editor['text'];
4072 $data->summaryformat = $data->summary_editor['format'];
4074 $data->id = $DB->insert_record('course_request', $data);
4076 // Create a new course_request object and return it
4077 $request = new course_request($data);
4079 // Notify the admin if required.
4080 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4082 $a = new stdClass;
4083 $a->link = "$CFG->wwwroot/course/pending.php";
4084 $a->user = fullname($USER);
4085 $subject = get_string('courserequest');
4086 $message = get_string('courserequestnotifyemail', 'admin', $a);
4087 foreach ($users as $user) {
4088 $request->notify($user, $USER, 'courserequested', $subject, $message);
4092 return $request;
4096 * Returns an array of options to use with a summary editor
4098 * @uses course_request::$summaryeditoroptions
4099 * @return array An array of options to use with the editor
4101 public static function summary_editor_options() {
4102 global $CFG;
4103 if (self::$summaryeditoroptions === null) {
4104 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4106 return self::$summaryeditoroptions;
4110 * Loads the properties for this course request object. Id is required and if
4111 * only id is provided then we load the rest of the properties from the database
4113 * @param stdClass|int $properties Either an object containing properties
4114 * or the course_request id to load
4116 public function __construct($properties) {
4117 global $DB;
4118 if (empty($properties->id)) {
4119 if (empty($properties)) {
4120 throw new coding_exception('You must provide a course request id when creating a course_request object');
4122 $id = $properties;
4123 $properties = new stdClass;
4124 $properties->id = (int)$id;
4125 unset($id);
4127 if (empty($properties->requester)) {
4128 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4129 print_error('unknowncourserequest');
4131 } else {
4132 $this->properties = $properties;
4134 $this->properties->collision = null;
4138 * Returns the requested property
4140 * @param string $key
4141 * @return mixed
4143 public function __get($key) {
4144 return $this->properties->$key;
4148 * Override this to ensure empty($request->blah) calls return a reliable answer...
4150 * This is required because we define the __get method
4152 * @param mixed $key
4153 * @return bool True is it not empty, false otherwise
4155 public function __isset($key) {
4156 return (!empty($this->properties->$key));
4160 * Returns the user who requested this course
4162 * Uses a static var to cache the results and cut down the number of db queries
4164 * @staticvar array $requesters An array of cached users
4165 * @return stdClass The user who requested the course
4167 public function get_requester() {
4168 global $DB;
4169 static $requesters= array();
4170 if (!array_key_exists($this->properties->requester, $requesters)) {
4171 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4173 return $requesters[$this->properties->requester];
4177 * Checks that the shortname used by the course does not conflict with any other
4178 * courses that exist
4180 * @param string|null $shortnamemark The string to append to the requests shortname
4181 * should a conflict be found
4182 * @return bool true is there is a conflict, false otherwise
4184 public function check_shortname_collision($shortnamemark = '[*]') {
4185 global $DB;
4187 if ($this->properties->collision !== null) {
4188 return $this->properties->collision;
4191 if (empty($this->properties->shortname)) {
4192 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4193 $this->properties->collision = false;
4194 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4195 if (!empty($shortnamemark)) {
4196 $this->properties->shortname .= ' '.$shortnamemark;
4198 $this->properties->collision = true;
4199 } else {
4200 $this->properties->collision = false;
4202 return $this->properties->collision;
4206 * This function approves the request turning it into a course
4208 * This function converts the course request into a course, at the same time
4209 * transferring any files used in the summary to the new course and then removing
4210 * the course request and the files associated with it.
4212 * @return int The id of the course that was created from this request
4214 public function approve() {
4215 global $CFG, $DB, $USER;
4217 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4219 $category = get_course_category($CFG->defaultrequestcategory);
4220 $courseconfig = get_config('moodlecourse');
4222 // Transfer appropriate settings
4223 $data = clone($this->properties);
4224 unset($data->id);
4225 unset($data->reason);
4226 unset($data->requester);
4228 // Set category
4229 $data->category = $category->id;
4230 $data->sortorder = $category->sortorder; // place as the first in category
4232 // Set misc settings
4233 $data->requested = 1;
4234 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
4235 $data->restrictmodules = 1;
4238 // Apply course default settings
4239 $data->format = $courseconfig->format;
4240 $data->numsections = $courseconfig->numsections;
4241 $data->hiddensections = $courseconfig->hiddensections;
4242 $data->newsitems = $courseconfig->newsitems;
4243 $data->showgrades = $courseconfig->showgrades;
4244 $data->showreports = $courseconfig->showreports;
4245 $data->maxbytes = $courseconfig->maxbytes;
4246 $data->groupmode = $courseconfig->groupmode;
4247 $data->groupmodeforce = $courseconfig->groupmodeforce;
4248 $data->visible = $courseconfig->visible;
4249 $data->visibleold = $data->visible;
4250 $data->lang = $courseconfig->lang;
4252 $course = create_course($data);
4253 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
4255 // add enrol instances
4256 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4257 if ($manual = enrol_get_plugin('manual')) {
4258 $manual->add_default_instance($course);
4262 // enrol the requester as teacher if necessary
4263 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4264 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4267 $this->delete();
4269 $a = new stdClass();
4270 $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
4271 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4272 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4274 return $course->id;
4278 * Reject a course request
4280 * This function rejects a course request, emailing the requesting user the
4281 * provided notice and then removing the request from the database
4283 * @param string $notice The message to display to the user
4285 public function reject($notice) {
4286 global $USER, $DB;
4287 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4288 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4289 $this->delete();
4293 * Deletes the course request and any associated files
4295 public function delete() {
4296 global $DB;
4297 $DB->delete_records('course_request', array('id' => $this->properties->id));
4301 * Send a message from one user to another using events_trigger
4303 * @param object $touser
4304 * @param object $fromuser
4305 * @param string $name
4306 * @param string $subject
4307 * @param string $message
4309 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4310 $eventdata = new stdClass();
4311 $eventdata->component = 'moodle';
4312 $eventdata->name = $name;
4313 $eventdata->userfrom = $fromuser;
4314 $eventdata->userto = $touser;
4315 $eventdata->subject = $subject;
4316 $eventdata->fullmessage = $message;
4317 $eventdata->fullmessageformat = FORMAT_PLAIN;
4318 $eventdata->fullmessagehtml = '';
4319 $eventdata->smallmessage = '';
4320 $eventdata->notification = 1;
4321 message_send($eventdata);
4326 * Return a list of page types
4327 * @param string $pagetype current page type
4328 * @param stdClass $parentcontext Block's parent context
4329 * @param stdClass $currentcontext Current context of block
4331 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4332 // if above course context ,display all course fomats
4333 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4334 if ($course->id == SITEID) {
4335 return array('*'=>get_string('page-x', 'pagetype'));
4336 } else {
4337 return array('*'=>get_string('page-x', 'pagetype'),
4338 'course-*'=>get_string('page-course-x', 'pagetype'),
4339 'course-view-*'=>get_string('page-course-view-x', 'pagetype')