weekly release 2.2.4+
[moodle.git] / course / lib.php
blob9801a8d73b877334120ec63021cb95f465cb4f15
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 $modulename . '" /> ' .
1622 $accesstext . '<span class="instancename">' .
1623 $instancename . $altname . '</span></a>';
1625 // If specified, display extra content after link
1626 if ($content) {
1627 $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) .
1628 '">' . $content . '</div>';
1630 } else {
1631 // No link, so display only content
1632 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1633 $accesstext . $content . '</div>';
1636 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1637 if (!isset($groupings)) {
1638 $groupings = groups_get_all_groupings($course->id);
1640 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1642 } else {
1643 $textclasses = $extraclasses;
1644 $textclasses .= ' dimmed_text';
1645 if ($textclasses) {
1646 $textcss = 'class="' . trim($textclasses) . '" ';
1647 } else {
1648 $textcss = '';
1650 $accesstext = '<span class="accesshide">' .
1651 get_string('notavailableyet', 'condition') .
1652 ': </span>';
1654 if ($url = $mod->get_url()) {
1655 // Display greyed-out text of link
1656 echo '<div ' . $textcss . $mod->extra .
1657 ' >' . '<img src="' . $mod->get_icon_url() .
1658 '" class="activityicon" alt="' .
1659 $modulename .
1660 '" /> <span>'. $instancename . $altname .
1661 '</span></div>';
1663 // Do not display content after link when it is greyed out like this.
1664 } else {
1665 // No link, so display only content (also greyed)
1666 $contentpart = '<div ' . $textcss . $mod->extra . '>' .
1667 $accesstext . $content . '</div>';
1671 // Module can put text after the link (e.g. forum unread)
1672 echo $mod->get_after_link();
1674 // If there is content but NO link (eg label), then display the
1675 // content here (BEFORE any icons). In this case cons must be
1676 // displayed after the content so that it makes more sense visually
1677 // and for accessibility reasons, e.g. if you have a one-line label
1678 // it should work similarly (at least in terms of ordering) to an
1679 // activity.
1680 if (empty($url)) {
1681 echo $contentpart;
1684 if ($isediting) {
1685 if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1686 if (! $mod->groupmodelink = $groupbuttonslink) {
1687 $mod->groupmode = $course->groupmode;
1690 } else {
1691 $mod->groupmode = false;
1693 echo '&nbsp;&nbsp;';
1694 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1695 echo $mod->get_after_edit_icons();
1698 // Completion
1699 $completion = $hidecompletion
1700 ? COMPLETION_TRACKING_NONE
1701 : $completioninfo->is_enabled($mod);
1702 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1703 !isguestuser() && $mod->uservisible) {
1704 $completiondata = $completioninfo->get_data($mod,true);
1705 $completionicon = '';
1706 if ($isediting) {
1707 switch ($completion) {
1708 case COMPLETION_TRACKING_MANUAL :
1709 $completionicon = 'manual-enabled'; break;
1710 case COMPLETION_TRACKING_AUTOMATIC :
1711 $completionicon = 'auto-enabled'; break;
1712 default: // wtf
1714 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1715 switch($completiondata->completionstate) {
1716 case COMPLETION_INCOMPLETE:
1717 $completionicon = 'manual-n'; break;
1718 case COMPLETION_COMPLETE:
1719 $completionicon = 'manual-y'; break;
1721 } else { // Automatic
1722 switch($completiondata->completionstate) {
1723 case COMPLETION_INCOMPLETE:
1724 $completionicon = 'auto-n'; break;
1725 case COMPLETION_COMPLETE:
1726 $completionicon = 'auto-y'; break;
1727 case COMPLETION_COMPLETE_PASS:
1728 $completionicon = 'auto-pass'; break;
1729 case COMPLETION_COMPLETE_FAIL:
1730 $completionicon = 'auto-fail'; break;
1733 if ($completionicon) {
1734 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1735 $formattedname = format_string($mod->name, true, array('context' => $modcontext));
1736 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
1737 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1738 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
1739 $newstate =
1740 $completiondata->completionstate==COMPLETION_COMPLETE
1741 ? COMPLETION_INCOMPLETE
1742 : COMPLETION_COMPLETE;
1743 // In manual mode the icon is a toggle form...
1745 // If this completion state is used by the
1746 // conditional activities system, we need to turn
1747 // off the JS.
1748 if (!empty($CFG->enableavailability) &&
1749 condition_info::completion_value_used_as_condition($course, $mod)) {
1750 $extraclass = ' preventjs';
1751 } else {
1752 $extraclass = '';
1754 echo "
1755 <form class='togglecompletion$extraclass' method='post' action='".$CFG->wwwroot."/course/togglecompletion.php'><div>
1756 <input type='hidden' name='id' value='{$mod->id}' />
1757 <input type='hidden' name='modulename' value='".s($mod->name)."' />
1758 <input type='hidden' name='sesskey' value='".sesskey()."' />
1759 <input type='hidden' name='completionstate' value='$newstate' />
1760 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1761 </div></form>";
1762 } else {
1763 // In auto mode, or when editing, the icon is just an image
1764 echo "<span class='autocompletion'>";
1765 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1770 // If there is content AND a link, then display the content here
1771 // (AFTER any icons). Otherwise it was displayed before
1772 if (!empty($url)) {
1773 echo $contentpart;
1776 // Show availability information (for someone who isn't allowed to
1777 // see the activity itself, or for staff)
1778 if (!$mod->uservisible) {
1779 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1780 } else if ($canviewhidden && !empty($CFG->enableavailability) && $mod->visible) {
1781 $ci = new condition_info($mod);
1782 $fullinfo = $ci->get_full_information();
1783 if($fullinfo) {
1784 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1785 ? 'userrestriction_visible'
1786 : 'userrestriction_hidden','condition',
1787 $fullinfo).'</div>';
1791 echo html_writer::end_tag('div');
1792 echo html_writer::end_tag('li')."\n";
1795 } elseif ($ismoving) {
1796 echo "<ul class=\"section\">\n";
1799 if ($ismoving) {
1800 echo '<li><a title="'.$strmovefull.'"'.
1801 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1802 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1803 ' alt="'.$strmovehere.'" /></a></li>
1806 if (!empty($section->sequence) || $ismoving) {
1807 echo "</ul><!--class='section'-->\n\n";
1812 * Prints the menus to add activities and resources.
1814 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1815 global $CFG, $OUTPUT;
1817 // check to see if user can add menus
1818 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1819 return false;
1822 $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
1824 $resources = array();
1825 $activities = array();
1827 foreach($modnames as $modname=>$modnamestr) {
1828 if (!course_allowed_module($course, $modname)) {
1829 continue;
1832 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1833 if (!file_exists($libfile)) {
1834 continue;
1836 include_once($libfile);
1837 $gettypesfunc = $modname.'_get_types';
1838 if (function_exists($gettypesfunc)) {
1839 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1840 if ($types = $gettypesfunc()) {
1841 $menu = array();
1842 $atype = null;
1843 $groupname = null;
1844 foreach($types as $type) {
1845 if ($type->typestr === '--') {
1846 continue;
1848 if (strpos($type->typestr, '--') === 0) {
1849 $groupname = str_replace('--', '', $type->typestr);
1850 continue;
1852 $type->type = str_replace('&amp;', '&', $type->type);
1853 if ($type->modclass == MOD_CLASS_RESOURCE) {
1854 $atype = MOD_CLASS_RESOURCE;
1856 $menu[$urlbase.$type->type] = $type->typestr;
1858 if (!is_null($groupname)) {
1859 if ($atype == MOD_CLASS_RESOURCE) {
1860 $resources[] = array($groupname=>$menu);
1861 } else {
1862 $activities[] = array($groupname=>$menu);
1864 } else {
1865 if ($atype == MOD_CLASS_RESOURCE) {
1866 $resources = array_merge($resources, $menu);
1867 } else {
1868 $activities = array_merge($activities, $menu);
1872 } else {
1873 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1874 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1875 $resources[$urlbase.$modname] = $modnamestr;
1876 } else {
1877 // all other archetypes are considered activity
1878 $activities[$urlbase.$modname] = $modnamestr;
1883 $straddactivity = get_string('addactivity');
1884 $straddresource = get_string('addresource');
1886 $output = '<div class="section_add_menus">';
1888 if (!$vertical) {
1889 $output .= '<div class="horizontal">';
1892 if (!empty($resources)) {
1893 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1894 $select->set_help_icon('resources');
1895 $output .= $OUTPUT->render($select);
1898 if (!empty($activities)) {
1899 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1900 $select->set_help_icon('activities');
1901 $output .= $OUTPUT->render($select);
1904 if (!$vertical) {
1905 $output .= '</div>';
1908 $output .= '</div>';
1910 if ($return) {
1911 return $output;
1912 } else {
1913 echo $output;
1918 * Return the course category context for the category with id $categoryid, except
1919 * that if $categoryid is 0, return the system context.
1921 * @param integer $categoryid a category id or 0.
1922 * @return object the corresponding context
1924 function get_category_or_system_context($categoryid) {
1925 if ($categoryid) {
1926 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1927 } else {
1928 return get_context_instance(CONTEXT_SYSTEM);
1933 * Gets the child categories of a given courses category. Uses a static cache
1934 * to make repeat calls efficient.
1936 * @param int $parentid the id of a course category.
1937 * @return array all the child course categories.
1939 function get_child_categories($parentid) {
1940 static $allcategories = null;
1942 // only fill in this variable the first time
1943 if (null == $allcategories) {
1944 $allcategories = array();
1946 $categories = get_categories();
1947 foreach ($categories as $category) {
1948 if (empty($allcategories[$category->parent])) {
1949 $allcategories[$category->parent] = array();
1951 $allcategories[$category->parent][] = $category;
1955 if (empty($allcategories[$parentid])) {
1956 return array();
1957 } else {
1958 return $allcategories[$parentid];
1963 * This function recursively travels the categories, building up a nice list
1964 * for display. It also makes an array that list all the parents for each
1965 * category.
1967 * For example, if you have a tree of categories like:
1968 * Miscellaneous (id = 1)
1969 * Subcategory (id = 2)
1970 * Sub-subcategory (id = 4)
1971 * Other category (id = 3)
1972 * Then after calling this function you will have
1973 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1974 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1975 * 3 => 'Other category');
1976 * $parents = array(2 => array(1), 4 => array(1, 2));
1978 * If you specify $requiredcapability, then only categories where the current
1979 * user has that capability will be added to $list, although all categories
1980 * will still be added to $parents, and if you only have $requiredcapability
1981 * in a child category, not the parent, then the child catgegory will still be
1982 * included.
1984 * If you specify the option $excluded, then that category, and all its children,
1985 * are omitted from the tree. This is useful when you are doing something like
1986 * moving categories, where you do not want to allow people to move a category
1987 * to be the child of itself.
1989 * @param array $list For output, accumulates an array categoryid => full category path name
1990 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1991 * @param string/array $requiredcapability if given, only categories where the current
1992 * user has this capability will be added to $list. Can also be an array of capabilities,
1993 * in which case they are all required.
1994 * @param integer $excludeid Omit this category and its children from the lists built.
1995 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1996 * @param string $path For internal use, as part of recursive calls.
1998 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1999 $excludeid = 0, $category = NULL, $path = "") {
2001 // initialize the arrays if needed
2002 if (!is_array($list)) {
2003 $list = array();
2005 if (!is_array($parents)) {
2006 $parents = array();
2009 if (empty($category)) {
2010 // Start at the top level.
2011 $category = new stdClass;
2012 $category->id = 0;
2013 } else {
2014 // This is the excluded category, don't include it.
2015 if ($excludeid > 0 && $excludeid == $category->id) {
2016 return;
2019 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2020 $categoryname = format_string($category->name, true, array('context' => $context));
2022 // Update $path.
2023 if ($path) {
2024 $path = $path.' / '.$categoryname;
2025 } else {
2026 $path = $categoryname;
2029 // Add this category to $list, if the permissions check out.
2030 if (empty($requiredcapability)) {
2031 $list[$category->id] = $path;
2033 } else {
2034 $requiredcapability = (array)$requiredcapability;
2035 if (has_all_capabilities($requiredcapability, $context)) {
2036 $list[$category->id] = $path;
2041 // Add all the children recursively, while updating the parents array.
2042 if ($categories = get_child_categories($category->id)) {
2043 foreach ($categories as $cat) {
2044 if (!empty($category->id)) {
2045 if (isset($parents[$category->id])) {
2046 $parents[$cat->id] = $parents[$category->id];
2048 $parents[$cat->id][] = $category->id;
2050 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
2056 * This function generates a structured array of courses and categories.
2058 * The depth of categories is limited by $CFG->maxcategorydepth however there
2059 * is no limit on the number of courses!
2061 * Suitable for use with the course renderers course_category_tree method:
2062 * $renderer = $PAGE->get_renderer('core','course');
2063 * echo $renderer->course_category_tree(get_course_category_tree());
2065 * @global moodle_database $DB
2066 * @param int $id
2067 * @param int $depth
2069 function get_course_category_tree($id = 0, $depth = 0) {
2070 global $DB, $CFG;
2071 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
2072 $categories = get_child_categories($id);
2073 $categoryids = array();
2074 foreach ($categories as $key => &$category) {
2075 if (!$category->visible && !$viewhiddencats) {
2076 unset($categories[$key]);
2077 continue;
2079 $categoryids[$category->id] = $category;
2080 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
2081 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
2082 foreach ($subcategories as $subid=>$subcat) {
2083 $categoryids[$subid] = $subcat;
2085 $category->courses = array();
2089 if ($depth > 0) {
2090 // This is a recursive call so return the required array
2091 return array($categories, $categoryids);
2094 if (empty($categoryids)) {
2095 // No categories available (probably all hidden).
2096 return array();
2099 // The depth is 0 this function has just been called so we can finish it off
2101 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
2102 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
2103 $sql = "SELECT
2104 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
2105 $ccselect
2106 FROM {course} c
2107 $ccjoin
2108 WHERE c.category $catsql ORDER BY c.sortorder ASC";
2109 if ($courses = $DB->get_records_sql($sql, $catparams)) {
2110 // loop throught them
2111 foreach ($courses as $course) {
2112 if ($course->id == SITEID) {
2113 continue;
2115 context_instance_preload($course);
2116 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
2117 $categoryids[$course->category]->courses[$course->id] = $course;
2121 return $categories;
2125 * Recursive function to print out all the categories in a nice format
2126 * with or without courses included
2128 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
2129 global $CFG;
2131 // maxcategorydepth == 0 meant no limit
2132 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
2133 return;
2136 if (!$displaylist) {
2137 make_categories_list($displaylist, $parentslist);
2140 if ($category) {
2141 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
2142 print_category_info($category, $depth, $showcourses);
2143 } else {
2144 return; // Don't bother printing children of invisible categories
2147 } else {
2148 $category = new stdClass();
2149 $category->id = "0";
2152 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
2153 $countcats = count($categories);
2154 $count = 0;
2155 $first = true;
2156 $last = false;
2157 foreach ($categories as $cat) {
2158 $count++;
2159 if ($count == $countcats) {
2160 $last = true;
2162 $up = $first ? false : true;
2163 $down = $last ? false : true;
2164 $first = false;
2166 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
2172 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
2174 function make_categories_options() {
2175 make_categories_list($cats,$parents);
2176 foreach ($cats as $key => $value) {
2177 if (array_key_exists($key,$parents)) {
2178 if ($indent = count($parents[$key])) {
2179 for ($i = 0; $i < $indent; $i++) {
2180 $cats[$key] = '&nbsp;'.$cats[$key];
2185 return $cats;
2189 * Prints the category info in indented fashion
2190 * This function is only used by print_whole_category_list() above
2192 function print_category_info($category, $depth=0, $showcourses = false) {
2193 global $CFG, $DB, $OUTPUT;
2195 $strsummary = get_string('summary');
2197 $catlinkcss = null;
2198 if (!$category->visible) {
2199 $catlinkcss = array('class'=>'dimmed');
2201 static $coursecount = null;
2202 if (null === $coursecount) {
2203 // only need to check this once
2204 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2207 if ($showcourses and $coursecount) {
2208 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2209 } else {
2210 $catimage = "&nbsp;";
2213 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2214 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2215 $fullname = format_string($category->name, true, array('context' => $context));
2217 if ($showcourses and $coursecount) {
2218 echo '<div class="categorylist clearfix">';
2219 $cat = '';
2220 $cat .= html_writer::tag('div', $catimage, array('class'=>'image'));
2221 $catlink = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2222 $cat .= html_writer::tag('div', $catlink, array('class'=>'name'));
2224 $html = '';
2225 if ($depth > 0) {
2226 for ($i=0; $i< $depth; $i++) {
2227 $html = html_writer::tag('div', $html . $cat, array('class'=>'indentation'));
2228 $cat = '';
2230 } else {
2231 $html = $cat;
2233 echo html_writer::tag('div', $html, array('class'=>'category'));
2234 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2236 // does the depth exceed maxcategorydepth
2237 // maxcategorydepth == 0 or unset meant no limit
2238 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2239 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2240 foreach ($courses as $course) {
2241 $linkcss = null;
2242 if (!$course->visible) {
2243 $linkcss = array('class'=>'dimmed');
2246 $coursename = get_course_display_name_for_list($course);
2247 $courselink = html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), format_string($coursename), $linkcss);
2249 // print enrol info
2250 $courseicon = '';
2251 if ($icons = enrol_get_course_info_icons($course)) {
2252 foreach ($icons as $pix_icon) {
2253 $courseicon = $OUTPUT->render($pix_icon).' ';
2257 $coursecontent = html_writer::tag('div', $courseicon.$courselink, array('class'=>'name'));
2259 if ($course->summary) {
2260 $link = new moodle_url('/course/info.php?id='.$course->id);
2261 $actionlink = $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2262 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2263 array('title'=>$strsummary));
2265 $coursecontent .= html_writer::tag('div', $actionlink, array('class'=>'info'));
2268 $html = '';
2269 for ($i=0; $i <= $depth; $i++) {
2270 $html = html_writer::tag('div', $html . $coursecontent , array('class'=>'indentation'));
2271 $coursecontent = '';
2273 echo html_writer::tag('div', $html, array('class'=>'course clearfloat'));
2276 echo '</div>';
2277 } else {
2278 echo '<div class="categorylist">';
2279 $html = '';
2280 $cat = html_writer::link(new moodle_url('/course/category.php', array('id'=>$category->id)), $fullname, $catlinkcss);
2281 if (count($courses) > 0) {
2282 $cat .= html_writer::tag('span', ' ('.count($courses).')', array('title'=>get_string('numberofcourses'), 'class'=>'numberofcourse'));
2285 if ($depth > 0) {
2286 for ($i=0; $i< $depth; $i++) {
2287 $html = html_writer::tag('div', $html .$cat, array('class'=>'indentation'));
2288 $cat = '';
2290 } else {
2291 $html = $cat;
2294 echo html_writer::tag('div', $html, array('class'=>'category'));
2295 echo html_writer::tag('div', '', array('class'=>'clearfloat'));
2296 echo '</div>';
2301 * Print the buttons relating to course requests.
2303 * @param object $systemcontext the system context.
2305 function print_course_request_buttons($systemcontext) {
2306 global $CFG, $DB, $OUTPUT;
2307 if (empty($CFG->enablecourserequests)) {
2308 return;
2310 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2311 /// Print a button to request a new course
2312 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2314 /// Print a button to manage pending requests
2315 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2316 $disabled = !$DB->record_exists('course_request', array());
2317 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2322 * Does the user have permission to edit things in this category?
2324 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2325 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2327 function can_edit_in_category($categoryid = 0) {
2328 $context = get_category_or_system_context($categoryid);
2329 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2333 * Prints the turn editing on/off button on course/index.php or course/category.php.
2335 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2336 * @return string HTML of the editing button, or empty string, if this user is not allowed
2337 * to see it.
2339 function update_category_button($categoryid = 0) {
2340 global $CFG, $PAGE, $OUTPUT;
2342 // Check permissions.
2343 if (!can_edit_in_category($categoryid)) {
2344 return '';
2347 // Work out the appropriate action.
2348 if ($PAGE->user_is_editing()) {
2349 $label = get_string('turneditingoff');
2350 $edit = 'off';
2351 } else {
2352 $label = get_string('turneditingon');
2353 $edit = 'on';
2356 // Generate the button HTML.
2357 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2358 if ($categoryid) {
2359 $options['id'] = $categoryid;
2360 $page = 'category.php';
2361 } else {
2362 $page = 'index.php';
2364 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2368 * Category is 0 (for all courses) or an object
2370 function print_courses($category) {
2371 global $CFG, $OUTPUT;
2373 if (!is_object($category) && $category==0) {
2374 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2375 if (is_array($categories) && count($categories) == 1) {
2376 $category = array_shift($categories);
2377 $courses = get_courses_wmanagers($category->id,
2378 'c.sortorder ASC',
2379 array('summary','summaryformat'));
2380 } else {
2381 $courses = get_courses_wmanagers('all',
2382 'c.sortorder ASC',
2383 array('summary','summaryformat'));
2385 unset($categories);
2386 } else {
2387 $courses = get_courses_wmanagers($category->id,
2388 'c.sortorder ASC',
2389 array('summary','summaryformat'));
2392 if ($courses) {
2393 echo html_writer::start_tag('ul', array('class'=>'unlist'));
2394 foreach ($courses as $course) {
2395 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2396 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2397 echo html_writer::start_tag('li');
2398 print_course($course);
2399 echo html_writer::end_tag('li');
2402 echo html_writer::end_tag('ul');
2403 } else {
2404 echo $OUTPUT->heading(get_string("nocoursesyet"));
2405 $context = get_context_instance(CONTEXT_SYSTEM);
2406 if (has_capability('moodle/course:create', $context)) {
2407 $options = array();
2408 if (!empty($category->id)) {
2409 $options['category'] = $category->id;
2410 } else {
2411 $options['category'] = $CFG->defaultrequestcategory;
2413 echo html_writer::start_tag('div', array('class'=>'addcoursebutton'));
2414 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2415 echo html_writer::end_tag('div');
2421 * Print a description of a course, suitable for browsing in a list.
2423 * @param object $course the course object.
2424 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2426 function print_course($course, $highlightterms = '') {
2427 global $CFG, $USER, $DB, $OUTPUT;
2429 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2431 // Rewrite file URLs so that they are correct
2432 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2434 echo html_writer::start_tag('div', array('class'=>'coursebox clearfix'));
2435 echo html_writer::start_tag('div', array('class'=>'info'));
2436 echo html_writer::start_tag('h3', array('class'=>'name'));
2438 $linkhref = new moodle_url('/course/view.php', array('id'=>$course->id));
2440 $coursename = get_course_display_name_for_list($course);
2441 $linktext = highlight($highlightterms, format_string($coursename));
2442 $linkparams = array('title'=>get_string('entercourse'));
2443 if (empty($course->visible)) {
2444 $linkparams['class'] = 'dimmed';
2446 echo html_writer::link($linkhref, $linktext, $linkparams);
2447 echo html_writer::end_tag('h3');
2449 /// first find all roles that are supposed to be displayed
2450 if (!empty($CFG->coursecontact)) {
2451 $managerroles = explode(',', $CFG->coursecontact);
2452 $namesarray = array();
2453 $rusers = array();
2455 if (!isset($course->managers)) {
2456 $rusers = get_role_users($managerroles, $context, true,
2457 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname,
2458 r.name AS rolename, r.sortorder, r.id AS roleid',
2459 'r.sortorder ASC, u.lastname ASC');
2460 } else {
2461 // use the managers array if we have it for perf reasosn
2462 // populate the datastructure like output of get_role_users();
2463 foreach ($course->managers as $manager) {
2464 $u = new stdClass();
2465 $u = $manager->user;
2466 $u->roleid = $manager->roleid;
2467 $u->rolename = $manager->rolename;
2469 $rusers[] = $u;
2473 /// Rename some of the role names if needed
2474 if (isset($context)) {
2475 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2478 $namesarray = array();
2479 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2480 foreach ($rusers as $ra) {
2481 if (isset($namesarray[$ra->id])) {
2482 // only display a user once with the higest sortorder role
2483 continue;
2486 if (isset($aliasnames[$ra->roleid])) {
2487 $ra->rolename = $aliasnames[$ra->roleid]->name;
2490 $fullname = fullname($ra, $canviewfullnames);
2491 $namesarray[$ra->id] = format_string($ra->rolename).': '.
2492 html_writer::link(new moodle_url('/user/view.php', array('id'=>$ra->id, 'course'=>SITEID)), $fullname);
2495 if (!empty($namesarray)) {
2496 echo html_writer::start_tag('ul', array('class'=>'teachers'));
2497 foreach ($namesarray as $name) {
2498 echo html_writer::tag('li', $name);
2500 echo html_writer::end_tag('ul');
2503 echo html_writer::end_tag('div'); // End of info div
2505 echo html_writer::start_tag('div', array('class'=>'summary'));
2506 $options = new stdClass();
2507 $options->noclean = true;
2508 $options->para = false;
2509 $options->overflowdiv = true;
2510 if (!isset($course->summaryformat)) {
2511 $course->summaryformat = FORMAT_MOODLE;
2513 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2514 if ($icons = enrol_get_course_info_icons($course)) {
2515 echo html_writer::start_tag('div', array('class'=>'enrolmenticons'));
2516 foreach ($icons as $icon) {
2517 echo $OUTPUT->render($icon);
2519 echo html_writer::end_tag('div'); // End of enrolmenticons div
2521 echo html_writer::end_tag('div'); // End of summary div
2522 echo html_writer::end_tag('div'); // End of coursebox div
2526 * Prints custom user information on the home page.
2527 * Over time this can include all sorts of information
2529 function print_my_moodle() {
2530 global $USER, $CFG, $DB, $OUTPUT;
2532 if (!isloggedin() or isguestuser()) {
2533 print_error('nopermissions', '', '', 'See My Moodle');
2536 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2537 $rhosts = array();
2538 $rcourses = array();
2539 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2540 $rcourses = get_my_remotecourses($USER->id);
2541 $rhosts = get_my_remotehosts();
2544 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2546 if (!empty($courses)) {
2547 echo '<ul class="unlist">';
2548 foreach ($courses as $course) {
2549 if ($course->id == SITEID) {
2550 continue;
2552 echo '<li>';
2553 print_course($course);
2554 echo "</li>\n";
2556 echo "</ul>\n";
2559 // MNET
2560 if (!empty($rcourses)) {
2561 // at the IDP, we know of all the remote courses
2562 foreach ($rcourses as $course) {
2563 print_remote_course($course, "100%");
2565 } elseif (!empty($rhosts)) {
2566 // non-IDP, we know of all the remote servers, but not courses
2567 foreach ($rhosts as $host) {
2568 print_remote_host($host, "100%");
2571 unset($course);
2572 unset($host);
2574 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2575 echo "<table width=\"100%\"><tr><td align=\"center\">";
2576 print_course_search("", false, "short");
2577 echo "</td><td align=\"center\">";
2578 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2579 echo "</td></tr></table>\n";
2582 } else {
2583 if ($DB->count_records("course_categories") > 1) {
2584 echo $OUTPUT->box_start("categorybox");
2585 print_whole_category_list();
2586 echo $OUTPUT->box_end();
2587 } else {
2588 print_courses(0);
2594 function print_course_search($value="", $return=false, $format="plain") {
2595 global $CFG;
2596 static $count = 0;
2598 $count++;
2600 $id = 'coursesearch';
2602 if ($count > 1) {
2603 $id .= $count;
2606 $strsearchcourses= get_string("searchcourses");
2608 if ($format == 'plain') {
2609 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2610 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2611 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2612 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2613 $output .= '<input type="submit" value="'.get_string('go').'" />';
2614 $output .= '</fieldset></form>';
2615 } else if ($format == 'short') {
2616 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2617 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2618 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2619 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2620 $output .= '<input type="submit" value="'.get_string('go').'" />';
2621 $output .= '</fieldset></form>';
2622 } else if ($format == 'navbar') {
2623 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2624 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2625 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2626 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2627 $output .= '<input type="submit" value="'.get_string('go').'" />';
2628 $output .= '</fieldset></form>';
2631 if ($return) {
2632 return $output;
2634 echo $output;
2637 function print_remote_course($course, $width="100%") {
2638 global $CFG, $USER;
2640 $linkcss = '';
2642 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2644 echo '<div class="coursebox remotecoursebox clearfix">';
2645 echo '<div class="info">';
2646 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2647 $linkcss.' href="'.$url.'">'
2648 . format_string($course->fullname) .'</a><br />'
2649 . format_string($course->hostname) . ' : '
2650 . format_string($course->cat_name) . ' : '
2651 . format_string($course->shortname). '</div>';
2652 echo '</div><div class="summary">';
2653 $options = new stdClass();
2654 $options->noclean = true;
2655 $options->para = false;
2656 $options->overflowdiv = true;
2657 echo format_text($course->summary, $course->summaryformat, $options);
2658 echo '</div>';
2659 echo '</div>';
2662 function print_remote_host($host, $width="100%") {
2663 global $OUTPUT;
2665 $linkcss = '';
2667 echo '<div class="coursebox clearfix">';
2668 echo '<div class="info">';
2669 echo '<div class="name">';
2670 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2671 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2672 . s($host['name']).'</a> - ';
2673 echo $host['count'] . ' ' . get_string('courses');
2674 echo '</div>';
2675 echo '</div>';
2676 echo '</div>';
2680 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2682 function add_course_module($mod) {
2683 global $DB;
2685 $mod->added = time();
2686 unset($mod->id);
2688 return $DB->insert_record("course_modules", $mod);
2692 * Returns course section - creates new if does not exist yet.
2693 * @param int $relative section number
2694 * @param int $courseid
2695 * @return object $course_section object
2697 function get_course_section($section, $courseid) {
2698 global $DB;
2700 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2701 return $cw;
2703 $cw = new stdClass();
2704 $cw->course = $courseid;
2705 $cw->section = $section;
2706 $cw->summary = "";
2707 $cw->summaryformat = FORMAT_HTML;
2708 $cw->sequence = "";
2709 $id = $DB->insert_record("course_sections", $cw);
2710 return $DB->get_record("course_sections", array("id"=>$id));
2713 * Given a full mod object with section and course already defined, adds this module to that section.
2715 * @param object $mod
2716 * @param int $beforemod An existing ID which we will insert the new module before
2717 * @return int The course_sections ID where the mod is inserted
2719 function add_mod_to_section($mod, $beforemod=NULL) {
2720 global $DB;
2722 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2724 $section->sequence = trim($section->sequence);
2726 if (empty($section->sequence)) {
2727 $newsequence = "$mod->coursemodule";
2729 } else if ($beforemod) {
2730 $modarray = explode(",", $section->sequence);
2732 if ($key = array_keys($modarray, $beforemod->id)) {
2733 $insertarray = array($mod->id, $beforemod->id);
2734 array_splice($modarray, $key[0], 1, $insertarray);
2735 $newsequence = implode(",", $modarray);
2737 } else { // Just tack it on the end anyway
2738 $newsequence = "$section->sequence,$mod->coursemodule";
2741 } else {
2742 $newsequence = "$section->sequence,$mod->coursemodule";
2745 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2746 return $section->id; // Return course_sections ID that was used.
2748 } else { // Insert a new record
2749 $section->course = $mod->course;
2750 $section->section = $mod->section;
2751 $section->summary = "";
2752 $section->summaryformat = FORMAT_HTML;
2753 $section->sequence = $mod->coursemodule;
2754 return $DB->insert_record("course_sections", $section);
2758 function set_coursemodule_groupmode($id, $groupmode) {
2759 global $DB;
2760 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2763 function set_coursemodule_idnumber($id, $idnumber) {
2764 global $DB;
2765 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2769 * $prevstateoverrides = true will set the visibility of the course module
2770 * to what is defined in visibleold. This enables us to remember the current
2771 * visibility when making a whole section hidden, so that when we toggle
2772 * that section back to visible, we are able to return the visibility of
2773 * the course module back to what it was originally.
2775 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2776 global $DB, $CFG;
2777 require_once($CFG->libdir.'/gradelib.php');
2779 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2780 return false;
2782 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2783 return false;
2785 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2786 foreach($events as $event) {
2787 if ($visible) {
2788 show_event($event);
2789 } else {
2790 hide_event($event);
2795 // hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there
2796 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
2797 if ($grade_items) {
2798 foreach ($grade_items as $grade_item) {
2799 $grade_item->set_hidden(!$visible);
2803 if ($prevstateoverrides) {
2804 if ($visible == '0') {
2805 // Remember the current visible state so we can toggle this back.
2806 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2807 } else {
2808 // Get the previous saved visible states.
2809 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2812 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2816 * Delete a course module and any associated data at the course level (events)
2817 * Until 1.5 this function simply marked a deleted flag ... now it
2818 * deletes it completely.
2821 function delete_course_module($id) {
2822 global $CFG, $DB;
2823 require_once($CFG->libdir.'/gradelib.php');
2824 require_once($CFG->dirroot.'/blog/lib.php');
2826 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2827 return true;
2829 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2830 //delete events from calendar
2831 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2832 foreach($events as $event) {
2833 delete_event($event->id);
2836 //delete grade items, outcome items and grades attached to modules
2837 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2838 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2839 foreach ($grade_items as $grade_item) {
2840 $grade_item->delete('moddelete');
2843 // Delete completion and availability data; it is better to do this even if the
2844 // features are not turned on, in case they were turned on previously (these will be
2845 // very quick on an empty table)
2846 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
2847 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
2848 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
2849 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
2851 delete_context(CONTEXT_MODULE, $cm->id);
2852 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2855 function delete_mod_from_section($mod, $section) {
2856 global $DB;
2858 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2860 $modarray = explode(",", $section->sequence);
2862 if ($key = array_keys ($modarray, $mod)) {
2863 array_splice($modarray, $key[0], 1);
2864 $newsequence = implode(",", $modarray);
2865 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2866 } else {
2867 return false;
2871 return false;
2875 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2877 * @param object $course course object
2878 * @param int $section Section number (not id!!!)
2879 * @param int $move (-1 or 1)
2880 * @return boolean true if section moved successfully
2882 function move_section($course, $section, $move) {
2883 /// Moves a whole course section up and down within the course
2884 global $USER, $DB;
2886 if (!$move) {
2887 return true;
2890 $sectiondest = $section + $move;
2892 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2893 return false;
2896 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2897 return false;
2900 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2901 return false;
2904 $DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id));
2905 $DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id));
2907 // Update highlighting if the move affects highlighted section
2908 if ($course->marker == $section) {
2909 course_set_marker($course->id, $sectiondest);
2910 } elseif ($course->marker == $sectiondest) {
2911 course_set_marker($course->id, $section);
2914 // if the focus is on the section that is being moved, then move the focus along
2915 if (course_get_display($course->id) == $section) {
2916 course_set_display($course->id, $sectiondest);
2919 // Check for duplicates and fix order if needed.
2920 // There is a very rare case that some sections in the same course have the same section id.
2921 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2922 $n = 0;
2923 foreach ($sections as $section) {
2924 if ($section->section != $n) {
2925 $DB->set_field('course_sections', 'section', $n, array('id'=>$section->id));
2927 $n++;
2929 return true;
2933 * Moves a section within a course, from a position to another.
2934 * Be very careful: $section and $destination refer to section number,
2935 * not id!.
2937 * @param object $course
2938 * @param int $section Section number (not id!!!)
2939 * @param int $destination
2940 * @return boolean Result
2942 function move_section_to($course, $section, $destination) {
2943 /// Moves a whole course section up and down within the course
2944 global $USER, $DB;
2946 if (!$destination && $destination != 0) {
2947 return true;
2950 if ($destination > $course->numsections) {
2951 return false;
2954 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2955 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2956 'section ASC, id ASC', 'id, section')) {
2957 return false;
2960 $sections = reorder_sections($sections, $section, $destination);
2962 // Update all sections
2963 foreach ($sections as $id => $position) {
2964 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2967 // if the focus is on the section that is being moved, then move the focus along
2968 if (course_get_display($course->id) == $section) {
2969 course_set_display($course->id, $destination);
2971 return true;
2975 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2976 * an original position number and a target position number, rebuilds the array so that the
2977 * move is made without any duplication of section positions.
2978 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2979 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2981 * @param array $sections
2982 * @param int $origin_position
2983 * @param int $target_position
2984 * @return array
2986 function reorder_sections($sections, $origin_position, $target_position) {
2987 if (!is_array($sections)) {
2988 return false;
2991 // We can't move section position 0
2992 if ($origin_position < 1) {
2993 echo "We can't move section position 0";
2994 return false;
2997 // Locate origin section in sections array
2998 if (!$origin_key = array_search($origin_position, $sections)) {
2999 echo "searched position not in sections array";
3000 return false; // searched position not in sections array
3003 // Extract origin section
3004 $origin_section = $sections[$origin_key];
3005 unset($sections[$origin_key]);
3007 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
3008 $found = false;
3009 $append_array = array();
3010 foreach ($sections as $id => $position) {
3011 if ($found) {
3012 $append_array[$id] = $position;
3013 unset($sections[$id]);
3015 if ($position == $target_position) {
3016 $found = true;
3020 // Append moved section
3021 $sections[$origin_key] = $origin_section;
3023 // Append rest of array (if applicable)
3024 if (!empty($append_array)) {
3025 foreach ($append_array as $id => $position) {
3026 $sections[$id] = $position;
3030 // Renumber positions
3031 $position = 0;
3032 foreach ($sections as $id => $p) {
3033 $sections[$id] = $position;
3034 $position++;
3037 return $sections;
3042 * Move the module object $mod to the specified $section
3043 * If $beforemod exists then that is the module
3044 * before which $modid should be inserted
3045 * All parameters are objects
3047 function moveto_module($mod, $section, $beforemod=NULL) {
3048 global $DB, $OUTPUT;
3050 /// Remove original module from original section
3051 if (! delete_mod_from_section($mod->id, $mod->section)) {
3052 echo $OUTPUT->notification("Could not delete module from existing section");
3055 /// Update module itself if necessary
3057 if ($mod->section != $section->id) {
3058 $mod->section = $section->id;
3059 $DB->update_record("course_modules", $mod);
3060 // if moving to a hidden section then hide module
3061 if (!$section->visible) {
3062 set_coursemodule_visible($mod->id, 0);
3066 /// Add the module into the new section
3068 $mod->course = $section->course;
3069 $mod->section = $section->section; // need relative reference
3070 $mod->coursemodule = $mod->id;
3072 if (! add_mod_to_section($mod, $beforemod)) {
3073 return false;
3076 return true;
3080 * Produces the editing buttons for a module
3082 * @global core_renderer $OUTPUT
3083 * @staticvar type $str
3084 * @param stdClass $mod The module to produce editing buttons for
3085 * @param bool $absolute_ignored ignored - all links are absolute
3086 * @param bool $moveselect If true a move seleciton process is used (default true)
3087 * @param int $indent The current indenting
3088 * @param int $section The section to link back to
3089 * @return string XHTML for the editing buttons
3091 function make_editing_buttons(stdClass $mod, $absolute_ignored = true, $moveselect = true, $indent=-1, $section=-1) {
3092 global $CFG, $OUTPUT;
3094 static $str;
3096 $coursecontext = get_context_instance(CONTEXT_COURSE, $mod->course);
3097 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
3099 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
3100 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
3102 // no permission to edit anything
3103 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
3104 return false;
3107 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
3109 if (!isset($str)) {
3110 $str = new stdClass;
3111 $str->assign = get_string("assignroles", 'role');
3112 $str->delete = get_string("delete");
3113 $str->move = get_string("move");
3114 $str->moveup = get_string("moveup");
3115 $str->movedown = get_string("movedown");
3116 $str->moveright = get_string("moveright");
3117 $str->moveleft = get_string("moveleft");
3118 $str->update = get_string("update");
3119 $str->duplicate = get_string("duplicate");
3120 $str->hide = get_string("hide");
3121 $str->show = get_string("show");
3122 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
3123 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
3124 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
3125 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
3126 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
3127 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
3130 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
3132 if ($section >= 0) {
3133 $baseurl->param('sr', $section);
3135 $actions = array();
3137 // leftright
3138 if ($hasmanageactivities) {
3139 if (right_to_left()) { // Exchange arrows on RTL
3140 $rightarrow = 't/left';
3141 $leftarrow = 't/right';
3142 } else {
3143 $rightarrow = 't/right';
3144 $leftarrow = 't/left';
3147 if ($indent > 0) {
3148 $actions[] = new action_link(
3149 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
3150 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall')),
3151 null,
3152 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
3155 if ($indent >= 0) {
3156 $actions[] = new action_link(
3157 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
3158 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall')),
3159 null,
3160 array('class' => 'editing_moveright', 'title' => $str->moveright)
3165 // move
3166 if ($hasmanageactivities) {
3167 if ($moveselect) {
3168 $actions[] = new action_link(
3169 new moodle_url($baseurl, array('copy' => $mod->id)),
3170 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall')),
3171 null,
3172 array('class' => 'editing_move', 'title' => $str->move)
3174 } else {
3175 $actions[] = new action_link(
3176 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '-1')),
3177 new pix_icon('t/up', $str->moveup, 'moodle', array('class' => 'iconsmall')),
3178 null,
3179 array('class' => 'editing_moveup', 'title' => $str->moveup)
3181 $actions[] = new action_link(
3182 new moodle_url($baseurl, array('id' => $mod->id, 'move' => '1')),
3183 new pix_icon('t/down', $str->movedown, 'moodle', array('class' => 'iconsmall')),
3184 null,
3185 array('class' => 'editing_movedown', 'title' => $str->movedown)
3190 // Update
3191 if ($hasmanageactivities) {
3192 $actions[] = new action_link(
3193 new moodle_url($baseurl, array('update' => $mod->id)),
3194 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall')),
3195 null,
3196 array('class' => 'editing_update', 'title' => $str->update)
3200 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
3201 if (has_all_capabilities($dupecaps, $coursecontext) && plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
3202 $actions[] = new action_link(
3203 new moodle_url($baseurl, array('duplicate' => $mod->id)),
3204 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall')),
3205 null,
3206 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
3210 // Delete
3211 if ($hasmanageactivities) {
3212 $actions[] = new action_link(
3213 new moodle_url($baseurl, array('delete' => $mod->id)),
3214 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall')),
3215 null,
3216 array('class' => 'editing_delete', 'title' => $str->delete)
3220 // hideshow
3221 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
3222 if ($mod->visible) {
3223 $actions[] = new action_link(
3224 new moodle_url($baseurl, array('hide' => $mod->id)),
3225 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall')),
3226 null,
3227 array('class' => 'editing_hide', 'title' => $str->hide)
3229 } else {
3230 $actions[] = new action_link(
3231 new moodle_url($baseurl, array('show' => $mod->id)),
3232 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall')),
3233 null,
3234 array('class' => 'editing_show', 'title' => $str->show)
3239 // groupmode
3240 if ($hasmanageactivities and $mod->groupmode !== false) {
3241 if ($mod->groupmode == SEPARATEGROUPS) {
3242 $groupmode = 0;
3243 $grouptitle = $str->groupsseparate;
3244 $forcedgrouptitle = $str->forcedgroupsseparate;
3245 $groupclass = 'editing_groupsseparate';
3246 $groupimage = 't/groups';
3247 } else if ($mod->groupmode == VISIBLEGROUPS) {
3248 $groupmode = 1;
3249 $grouptitle = $str->groupsvisible;
3250 $forcedgrouptitle = $str->forcedgroupsvisible;
3251 $groupclass = 'editing_groupsvisible';
3252 $groupimage = 't/groupv';
3253 } else {
3254 $groupmode = 2;
3255 $grouptitle = $str->groupsnone;
3256 $forcedgrouptitle = $str->forcedgroupsnone;
3257 $groupclass = 'editing_groupsnone';
3258 $groupimage = 't/groupn';
3260 if ($mod->groupmodelink) {
3261 $actions[] = new action_link(
3262 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
3263 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
3264 null,
3265 array('class' => $groupclass, 'title' => $grouptitle)
3267 } else {
3268 $actions[] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3272 // Assign
3273 if (has_capability('moodle/role:assign', $modcontext)){
3274 $actions[] = new action_link(
3275 new moodle_url('/'.$CFG->admin.'/roles/assign.php', array('contextid' => $modcontext->id)),
3276 new pix_icon('i/roles', $str->assign, 'moodle', array('class' => 'iconsmall')),
3277 null,
3278 array('class' => 'editing_assign', 'title' => $str->assign)
3282 $output = html_writer::start_tag('span', array('class' => 'commands'));
3283 foreach ($actions as $action) {
3284 if ($action instanceof renderable) {
3285 $output .= $OUTPUT->render($action);
3286 } else {
3287 $output .= $action;
3290 $output .= html_writer::end_tag('span');
3291 return $output;
3295 * given a course object with shortname & fullname, this function will
3296 * truncate the the number of chars allowed and add ... if it was too long
3298 function course_format_name ($course,$max=100) {
3300 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3301 $shortname = format_string($course->shortname, true, array('context' => $context));
3302 $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
3303 $str = $shortname.': '. $fullname;
3304 if (textlib::strlen($str) <= $max) {
3305 return $str;
3307 else {
3308 return textlib::substr($str,0,$max-3).'...';
3312 function update_restricted_mods($course, $mods) {
3313 global $DB;
3315 /// Delete all the current restricted list
3316 $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
3318 if (empty($course->restrictmodules)) {
3319 return; // We're done
3322 /// Insert the new list of restricted mods
3323 foreach ($mods as $mod) {
3324 if ($mod == 0) {
3325 continue; // this is the 'allow none' option
3327 $am = new stdClass();
3328 $am->course = $course->id;
3329 $am->module = $mod;
3330 $DB->insert_record('course_allowed_modules',$am);
3335 * This function will take an int (module id) or a string (module name)
3336 * and return true or false, whether it's allowed in the given course (object)
3337 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3338 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3341 function course_allowed_module($course,$mod) {
3342 global $DB;
3344 if (empty($course->restrictmodules)) {
3345 return true;
3348 // Admins and admin-like people who can edit everything can also add anything.
3349 // Originally there was a course:update test only, but it did not match the test in course edit form
3350 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3351 return true;
3354 if (is_numeric($mod)) {
3355 $modid = $mod;
3356 } else if (is_string($mod)) {
3357 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3359 if (empty($modid)) {
3360 return false;
3363 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
3367 * Recursively delete category including all subcategories and courses.
3368 * @param stdClass $category
3369 * @param boolean $showfeedback display some notices
3370 * @return array return deleted courses
3372 function category_delete_full($category, $showfeedback=true) {
3373 global $CFG, $DB;
3374 require_once($CFG->libdir.'/gradelib.php');
3375 require_once($CFG->libdir.'/questionlib.php');
3376 require_once($CFG->dirroot.'/cohort/lib.php');
3378 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3379 foreach ($children as $childcat) {
3380 category_delete_full($childcat, $showfeedback);
3384 $deletedcourses = array();
3385 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3386 foreach ($courses as $course) {
3387 if (!delete_course($course, false)) {
3388 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3390 $deletedcourses[] = $course;
3394 // move or delete cohorts in this context
3395 cohort_delete_category($category);
3397 // now delete anything that may depend on course category context
3398 grade_course_category_delete($category->id, 0, $showfeedback);
3399 if (!question_delete_course_category($category, 0, $showfeedback)) {
3400 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3403 // finally delete the category and it's context
3404 $DB->delete_records('course_categories', array('id'=>$category->id));
3405 delete_context(CONTEXT_COURSECAT, $category->id);
3407 events_trigger('course_category_deleted', $category);
3409 return $deletedcourses;
3413 * Delete category, but move contents to another category.
3414 * @param object $ccategory
3415 * @param int $newparentid category id
3416 * @return bool status
3418 function category_delete_move($category, $newparentid, $showfeedback=true) {
3419 global $CFG, $DB, $OUTPUT;
3420 require_once($CFG->libdir.'/gradelib.php');
3421 require_once($CFG->libdir.'/questionlib.php');
3422 require_once($CFG->dirroot.'/cohort/lib.php');
3424 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3425 return false;
3428 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3429 foreach ($children as $childcat) {
3430 move_category($childcat, $newparentcat);
3434 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3435 if (!move_courses(array_keys($courses), $newparentid)) {
3436 echo $OUTPUT->notification("Error moving courses");
3437 return false;
3439 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3442 // move or delete cohorts in this context
3443 cohort_delete_category($category);
3445 // now delete anything that may depend on course category context
3446 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3447 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3448 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3449 return false;
3452 // finally delete the category and it's context
3453 $DB->delete_records('course_categories', array('id'=>$category->id));
3454 delete_context(CONTEXT_COURSECAT, $category->id);
3456 events_trigger('course_category_deleted', $category);
3458 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3460 return true;
3464 * Efficiently moves many courses around while maintaining
3465 * sortorder in order.
3467 * @param array $courseids is an array of course ids
3468 * @param int $categoryid
3469 * @return bool success
3471 function move_courses($courseids, $categoryid) {
3472 global $CFG, $DB, $OUTPUT;
3474 if (empty($courseids)) {
3475 // nothing to do
3476 return;
3479 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3480 return false;
3483 $courseids = array_reverse($courseids);
3484 $newparent = get_context_instance(CONTEXT_COURSECAT, $category->id);
3485 $i = 1;
3487 foreach ($courseids as $courseid) {
3488 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3489 $course = new stdClass();
3490 $course->id = $courseid;
3491 $course->category = $category->id;
3492 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3493 if ($category->visible == 0) {
3494 // hide the course when moving into hidden category,
3495 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3496 $course->visible = 0;
3499 $DB->update_record('course', $course);
3501 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3502 context_moved($context, $newparent);
3505 fix_course_sortorder();
3507 return true;
3511 * Hide course category and child course and subcategories
3512 * @param stdClass $category
3513 * @return void
3515 function course_category_hide($category) {
3516 global $DB;
3518 $category->visible = 0;
3519 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3520 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3521 $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
3522 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3523 // get all child categories and hide too
3524 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3525 foreach ($subcats as $cat) {
3526 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3527 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3528 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3529 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3535 * Show course category and child course and subcategories
3536 * @param stdClass $category
3537 * @return void
3539 function course_category_show($category) {
3540 global $DB;
3542 $category->visible = 1;
3543 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3544 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3545 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3546 // get all child categories and unhide too
3547 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3548 foreach ($subcats as $cat) {
3549 if ($cat->visibleold) {
3550 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3552 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3558 * Efficiently moves a category - NOTE that this can have
3559 * a huge impact access-control-wise...
3561 function move_category($category, $newparentcat) {
3562 global $CFG, $DB;
3564 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3566 $hidecat = false;
3567 if (empty($newparentcat->id)) {
3568 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3570 $newparent = get_context_instance(CONTEXT_SYSTEM);
3572 } else {
3573 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3574 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3576 if (!$newparentcat->visible and $category->visible) {
3577 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3578 $hidecat = true;
3582 context_moved($context, $newparent);
3584 // now make it last in new category
3585 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3587 // and fix the sortorders
3588 fix_course_sortorder();
3590 if ($hidecat) {
3591 course_category_hide($category);
3596 * Returns the display name of the given section that the course prefers.
3598 * This function utilizes a callback that can be implemented within the course
3599 * formats lib.php file to customize the display name that is used to reference
3600 * the section.
3602 * By default (if callback is not defined) the method
3603 * {@see get_numeric_section_name} is called instead.
3605 * @param stdClass $course The course to get the section name for
3606 * @param stdClass $section Section object from database
3607 * @return Display name that the course format prefers, e.g. "Week 2"
3609 * @see get_generic_section_name
3611 function get_section_name(stdClass $course, stdClass $section) {
3612 global $CFG;
3614 /// Inelegant hack for bug 3408
3615 if ($course->format == 'site') {
3616 return get_string('site');
3619 // Use course formatter callback if it exists
3620 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3621 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3622 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3623 require_once $namingfile;
3625 if (function_exists($namingfunction)) {
3626 return $namingfunction($course, $section);
3629 // else, default behavior:
3630 return get_generic_section_name($course->format, $section);
3634 * Gets the generic section name for a courses section.
3636 * @param string $format Course format ID e.g. 'weeks' $course->format
3637 * @param stdClass $section Section object from database
3638 * @return Display name that the course format prefers, e.g. "Week 2"
3640 function get_generic_section_name($format, stdClass $section) {
3641 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3645 function course_format_uses_sections($format) {
3646 global $CFG;
3648 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3649 $featurefunction = 'callback_'.$format.'_uses_sections';
3650 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3651 require_once $featurefile;
3653 if (function_exists($featurefunction)) {
3654 return $featurefunction();
3657 return false;
3661 * Returns the information about the ajax support in the given source format
3663 * The returned object's property (boolean)capable indicates that
3664 * the course format supports Moodle course ajax features.
3665 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
3667 * @param string $format
3668 * @return stdClass
3670 function course_format_ajax_support($format) {
3671 global $CFG;
3673 // set up default values
3674 $ajaxsupport = new stdClass();
3675 $ajaxsupport->capable = false;
3676 $ajaxsupport->testedbrowsers = array();
3678 // get the information from the course format library
3679 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3680 $featurefunction = 'callback_'.$format.'_ajax_support';
3681 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3682 require_once $featurefile;
3684 if (function_exists($featurefunction)) {
3685 $formatsupport = $featurefunction();
3686 if (isset($formatsupport->capable)) {
3687 $ajaxsupport->capable = $formatsupport->capable;
3689 if (is_array($formatsupport->testedbrowsers)) {
3690 $ajaxsupport->testedbrowsers = $formatsupport->testedbrowsers;
3694 return $ajaxsupport;
3698 * Can the current user delete this course?
3699 * Course creators have exception,
3700 * 1 day after the creation they can sill delete the course.
3701 * @param int $courseid
3702 * @return boolean
3704 function can_delete_course($courseid) {
3705 global $USER, $DB;
3707 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3709 if (has_capability('moodle/course:delete', $context)) {
3710 return true;
3713 // hack: now try to find out if creator created this course recently (1 day)
3714 if (!has_capability('moodle/course:create', $context)) {
3715 return false;
3718 $since = time() - 60*60*24;
3720 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3721 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3723 return $DB->record_exists_select('log', $select, $params);
3727 * Save the Your name for 'Some role' strings.
3729 * @param integer $courseid the id of this course.
3730 * @param array $data the data that came from the course settings form.
3732 function save_local_role_names($courseid, $data) {
3733 global $DB;
3734 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3736 foreach ($data as $fieldname => $value) {
3737 if (strpos($fieldname, 'role_') !== 0) {
3738 continue;
3740 list($ignored, $roleid) = explode('_', $fieldname);
3742 // make up our mind whether we want to delete, update or insert
3743 if (!$value) {
3744 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3746 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3747 $rolename->name = $value;
3748 $DB->update_record('role_names', $rolename);
3750 } else {
3751 $rolename = new stdClass;
3752 $rolename->contextid = $context->id;
3753 $rolename->roleid = $roleid;
3754 $rolename->name = $value;
3755 $DB->insert_record('role_names', $rolename);
3761 * Create a course and either return a $course object
3763 * Please note this functions does not verify any access control,
3764 * the calling code is responsible for all validation (usually it is the form definition).
3766 * @param array $editoroptions course description editor options
3767 * @param object $data - all the data needed for an entry in the 'course' table
3768 * @return object new course instance
3770 function create_course($data, $editoroptions = NULL) {
3771 global $CFG, $DB;
3773 //check the categoryid - must be given for all new courses
3774 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3776 //check if the shortname already exist
3777 if (!empty($data->shortname)) {
3778 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3779 throw new moodle_exception('shortnametaken');
3783 //check if the id number already exist
3784 if (!empty($data->idnumber)) {
3785 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3786 throw new moodle_exception('idnumbertaken');
3790 $data->timecreated = time();
3791 $data->timemodified = $data->timecreated;
3793 // place at beginning of any category
3794 $data->sortorder = 0;
3796 if ($editoroptions) {
3797 // summary text is updated later, we need context to store the files first
3798 $data->summary = '';
3799 $data->summary_format = FORMAT_HTML;
3802 if (!isset($data->visible)) {
3803 // data not from form, add missing visibility info
3804 $data->visible = $category->visible;
3806 $data->visibleold = $data->visible;
3808 $newcourseid = $DB->insert_record('course', $data);
3809 $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
3811 if ($editoroptions) {
3812 // Save the files used in the summary editor and store
3813 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3814 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3815 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3818 $course = $DB->get_record('course', array('id'=>$newcourseid));
3820 // Setup the blocks
3821 blocks_add_default_course_blocks($course);
3823 $section = new stdClass();
3824 $section->course = $course->id; // Create a default section.
3825 $section->section = 0;
3826 $section->summaryformat = FORMAT_HTML;
3827 $DB->insert_record('course_sections', $section);
3829 fix_course_sortorder();
3831 // update module restrictions
3832 if ($course->restrictmodules || $CFG->restrictbydefault ) {
3833 if (isset($data->allowedmods)) {
3834 update_restricted_mods($course, $data->allowedmods);
3835 } else {
3836 if (!empty($CFG->defaultallowedmodules)) {
3837 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
3842 // new context created - better mark it as dirty
3843 mark_context_dirty($context->path);
3845 // Save any custom role names.
3846 save_local_role_names($course->id, (array)$data);
3848 // set up enrolments
3849 enrol_course_updated(true, $course, $data);
3851 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3853 // Trigger events
3854 events_trigger('course_created', $course);
3856 return $course;
3860 * Update a course.
3862 * Please note this functions does not verify any access control,
3863 * the calling code is responsible for all validation (usually it is the form definition).
3865 * @param object $data - all the data needed for an entry in the 'course' table
3866 * @param array $editoroptions course description editor options
3867 * @return void
3869 function update_course($data, $editoroptions = NULL) {
3870 global $CFG, $DB;
3872 $data->timemodified = time();
3874 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
3875 $context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
3877 if ($editoroptions) {
3878 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3881 if (!isset($data->category) or empty($data->category)) {
3882 // prevent nulls and 0 in category field
3883 unset($data->category);
3885 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3887 if (!isset($data->visible)) {
3888 // data not from form, add missing visibility info
3889 $data->visible = $oldcourse->visible;
3892 if ($data->visible != $oldcourse->visible) {
3893 // reset the visibleold flag when manually hiding/unhiding course
3894 $data->visibleold = $data->visible;
3895 } else {
3896 if ($movecat) {
3897 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3898 if (empty($newcategory->visible)) {
3899 // make sure when moving into hidden category the course is hidden automatically
3900 $data->visible = 0;
3905 // Update with the new data
3906 $DB->update_record('course', $data);
3908 $course = $DB->get_record('course', array('id'=>$data->id));
3910 if ($movecat) {
3911 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3912 context_moved($context, $newparent);
3915 fix_course_sortorder();
3917 // Test for and remove blocks which aren't appropriate anymore
3918 blocks_remove_inappropriate($course);
3920 // update module restrictions
3921 if (isset($data->allowedmods)) {
3922 update_restricted_mods($course, $data->allowedmods);
3925 // Save any custom role names.
3926 save_local_role_names($course->id, $data);
3928 // update enrol settings
3929 enrol_course_updated(false, $course, $data);
3931 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3933 // Trigger events
3934 events_trigger('course_updated', $course);
3938 * Average number of participants
3939 * @return integer
3941 function average_number_of_participants() {
3942 global $DB, $SITE;
3944 //count total of enrolments for visible course (except front page)
3945 $sql = 'SELECT COUNT(*) FROM (
3946 SELECT DISTINCT ue.userid, e.courseid
3947 FROM {user_enrolments} ue, {enrol} e, {course} c
3948 WHERE ue.enrolid = e.id
3949 AND e.courseid <> :siteid
3950 AND c.id = e.courseid
3951 AND c.visible = 1) as total';
3952 $params = array('siteid' => $SITE->id);
3953 $enrolmenttotal = $DB->count_records_sql($sql, $params);
3956 //count total of visible courses (minus front page)
3957 $coursetotal = $DB->count_records('course', array('visible' => 1));
3958 $coursetotal = $coursetotal - 1 ;
3960 //average of enrolment
3961 if (empty($coursetotal)) {
3962 $participantaverage = 0;
3963 } else {
3964 $participantaverage = $enrolmenttotal / $coursetotal;
3967 return $participantaverage;
3971 * Average number of course modules
3972 * @return integer
3974 function average_number_of_courses_modules() {
3975 global $DB, $SITE;
3977 //count total of visible course module (except front page)
3978 $sql = 'SELECT COUNT(*) FROM (
3979 SELECT cm.course, cm.module
3980 FROM {course} c, {course_modules} cm
3981 WHERE c.id = cm.course
3982 AND c.id <> :siteid
3983 AND cm.visible = 1
3984 AND c.visible = 1) as total';
3985 $params = array('siteid' => $SITE->id);
3986 $moduletotal = $DB->count_records_sql($sql, $params);
3989 //count total of visible courses (minus front page)
3990 $coursetotal = $DB->count_records('course', array('visible' => 1));
3991 $coursetotal = $coursetotal - 1 ;
3993 //average of course module
3994 if (empty($coursetotal)) {
3995 $coursemoduleaverage = 0;
3996 } else {
3997 $coursemoduleaverage = $moduletotal / $coursetotal;
4000 return $coursemoduleaverage;
4004 * This class pertains to course requests and contains methods associated with
4005 * create, approving, and removing course requests.
4007 * Please note we do not allow embedded images here because there is no context
4008 * to store them with proper access control.
4010 * @copyright 2009 Sam Hemelryk
4011 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4012 * @since Moodle 2.0
4014 * @property-read int $id
4015 * @property-read string $fullname
4016 * @property-read string $shortname
4017 * @property-read string $summary
4018 * @property-read int $summaryformat
4019 * @property-read int $summarytrust
4020 * @property-read string $reason
4021 * @property-read int $requester
4023 class course_request {
4026 * This is the stdClass that stores the properties for the course request
4027 * and is externally accessed through the __get magic method
4028 * @var stdClass
4030 protected $properties;
4033 * An array of options for the summary editor used by course request forms.
4034 * This is initially set by {@link summary_editor_options()}
4035 * @var array
4036 * @static
4038 protected static $summaryeditoroptions;
4041 * Static function to prepare the summary editor for working with a course
4042 * request.
4044 * @static
4045 * @param null|stdClass $data Optional, an object containing the default values
4046 * for the form, these may be modified when preparing the
4047 * editor so this should be called before creating the form
4048 * @return stdClass An object that can be used to set the default values for
4049 * an mforms form
4051 public static function prepare($data=null) {
4052 if ($data === null) {
4053 $data = new stdClass;
4055 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
4056 return $data;
4060 * Static function to create a new course request when passed an array of properties
4061 * for it.
4063 * This function also handles saving any files that may have been used in the editor
4065 * @static
4066 * @param stdClass $data
4067 * @return course_request The newly created course request
4069 public static function create($data) {
4070 global $USER, $DB, $CFG;
4071 $data->requester = $USER->id;
4073 // Summary is a required field so copy the text over
4074 $data->summary = $data->summary_editor['text'];
4075 $data->summaryformat = $data->summary_editor['format'];
4077 $data->id = $DB->insert_record('course_request', $data);
4079 // Create a new course_request object and return it
4080 $request = new course_request($data);
4082 // Notify the admin if required.
4083 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
4085 $a = new stdClass;
4086 $a->link = "$CFG->wwwroot/course/pending.php";
4087 $a->user = fullname($USER);
4088 $subject = get_string('courserequest');
4089 $message = get_string('courserequestnotifyemail', 'admin', $a);
4090 foreach ($users as $user) {
4091 $request->notify($user, $USER, 'courserequested', $subject, $message);
4095 return $request;
4099 * Returns an array of options to use with a summary editor
4101 * @uses course_request::$summaryeditoroptions
4102 * @return array An array of options to use with the editor
4104 public static function summary_editor_options() {
4105 global $CFG;
4106 if (self::$summaryeditoroptions === null) {
4107 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
4109 return self::$summaryeditoroptions;
4113 * Loads the properties for this course request object. Id is required and if
4114 * only id is provided then we load the rest of the properties from the database
4116 * @param stdClass|int $properties Either an object containing properties
4117 * or the course_request id to load
4119 public function __construct($properties) {
4120 global $DB;
4121 if (empty($properties->id)) {
4122 if (empty($properties)) {
4123 throw new coding_exception('You must provide a course request id when creating a course_request object');
4125 $id = $properties;
4126 $properties = new stdClass;
4127 $properties->id = (int)$id;
4128 unset($id);
4130 if (empty($properties->requester)) {
4131 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
4132 print_error('unknowncourserequest');
4134 } else {
4135 $this->properties = $properties;
4137 $this->properties->collision = null;
4141 * Returns the requested property
4143 * @param string $key
4144 * @return mixed
4146 public function __get($key) {
4147 return $this->properties->$key;
4151 * Override this to ensure empty($request->blah) calls return a reliable answer...
4153 * This is required because we define the __get method
4155 * @param mixed $key
4156 * @return bool True is it not empty, false otherwise
4158 public function __isset($key) {
4159 return (!empty($this->properties->$key));
4163 * Returns the user who requested this course
4165 * Uses a static var to cache the results and cut down the number of db queries
4167 * @staticvar array $requesters An array of cached users
4168 * @return stdClass The user who requested the course
4170 public function get_requester() {
4171 global $DB;
4172 static $requesters= array();
4173 if (!array_key_exists($this->properties->requester, $requesters)) {
4174 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
4176 return $requesters[$this->properties->requester];
4180 * Checks that the shortname used by the course does not conflict with any other
4181 * courses that exist
4183 * @param string|null $shortnamemark The string to append to the requests shortname
4184 * should a conflict be found
4185 * @return bool true is there is a conflict, false otherwise
4187 public function check_shortname_collision($shortnamemark = '[*]') {
4188 global $DB;
4190 if ($this->properties->collision !== null) {
4191 return $this->properties->collision;
4194 if (empty($this->properties->shortname)) {
4195 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
4196 $this->properties->collision = false;
4197 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
4198 if (!empty($shortnamemark)) {
4199 $this->properties->shortname .= ' '.$shortnamemark;
4201 $this->properties->collision = true;
4202 } else {
4203 $this->properties->collision = false;
4205 return $this->properties->collision;
4209 * This function approves the request turning it into a course
4211 * This function converts the course request into a course, at the same time
4212 * transferring any files used in the summary to the new course and then removing
4213 * the course request and the files associated with it.
4215 * @return int The id of the course that was created from this request
4217 public function approve() {
4218 global $CFG, $DB, $USER;
4220 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
4222 $category = get_course_category($CFG->defaultrequestcategory);
4223 $courseconfig = get_config('moodlecourse');
4225 // Transfer appropriate settings
4226 $data = clone($this->properties);
4227 unset($data->id);
4228 unset($data->reason);
4229 unset($data->requester);
4231 // Set category
4232 $data->category = $category->id;
4233 $data->sortorder = $category->sortorder; // place as the first in category
4235 // Set misc settings
4236 $data->requested = 1;
4237 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
4238 $data->restrictmodules = 1;
4241 // Apply course default settings
4242 $data->format = $courseconfig->format;
4243 $data->numsections = $courseconfig->numsections;
4244 $data->hiddensections = $courseconfig->hiddensections;
4245 $data->newsitems = $courseconfig->newsitems;
4246 $data->showgrades = $courseconfig->showgrades;
4247 $data->showreports = $courseconfig->showreports;
4248 $data->maxbytes = $courseconfig->maxbytes;
4249 $data->groupmode = $courseconfig->groupmode;
4250 $data->groupmodeforce = $courseconfig->groupmodeforce;
4251 $data->visible = $courseconfig->visible;
4252 $data->visibleold = $data->visible;
4253 $data->lang = $courseconfig->lang;
4255 $course = create_course($data);
4256 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
4258 // add enrol instances
4259 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
4260 if ($manual = enrol_get_plugin('manual')) {
4261 $manual->add_default_instance($course);
4265 // enrol the requester as teacher if necessary
4266 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
4267 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
4270 $this->delete();
4272 $a = new stdClass();
4273 $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
4274 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
4275 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
4277 return $course->id;
4281 * Reject a course request
4283 * This function rejects a course request, emailing the requesting user the
4284 * provided notice and then removing the request from the database
4286 * @param string $notice The message to display to the user
4288 public function reject($notice) {
4289 global $USER, $DB;
4290 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
4291 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
4292 $this->delete();
4296 * Deletes the course request and any associated files
4298 public function delete() {
4299 global $DB;
4300 $DB->delete_records('course_request', array('id' => $this->properties->id));
4304 * Send a message from one user to another using events_trigger
4306 * @param object $touser
4307 * @param object $fromuser
4308 * @param string $name
4309 * @param string $subject
4310 * @param string $message
4312 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
4313 $eventdata = new stdClass();
4314 $eventdata->component = 'moodle';
4315 $eventdata->name = $name;
4316 $eventdata->userfrom = $fromuser;
4317 $eventdata->userto = $touser;
4318 $eventdata->subject = $subject;
4319 $eventdata->fullmessage = $message;
4320 $eventdata->fullmessageformat = FORMAT_PLAIN;
4321 $eventdata->fullmessagehtml = '';
4322 $eventdata->smallmessage = '';
4323 $eventdata->notification = 1;
4324 message_send($eventdata);
4329 * Return a list of page types
4330 * @param string $pagetype current page type
4331 * @param stdClass $parentcontext Block's parent context
4332 * @param stdClass $currentcontext Current context of block
4334 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
4335 // if above course context ,display all course fomats
4336 list($currentcontext, $course, $cm) = get_context_info_array($currentcontext->id);
4337 if ($course->id == SITEID) {
4338 return array('*'=>get_string('page-x', 'pagetype'));
4339 } else {
4340 return array('*'=>get_string('page-x', 'pagetype'),
4341 'course-*'=>get_string('page-course-x', 'pagetype'),
4342 'course-view-*'=>get_string('page-course-view-x', 'pagetype')