MDL-20808 "Create AMF test client" Some updates to client
[moodle.git] / course / lib.php
blobaf19fc2d26202d588f896ea8b3147c11282b869c
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_LOG_DISPLAY', 150); // days
33 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
34 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
35 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
36 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
37 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
38 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
39 define('FRONTPAGENEWS', '0');
40 define('FRONTPAGECOURSELIST', '1');
41 define('FRONTPAGECATEGORYNAMES', '2');
42 define('FRONTPAGETOPICONLY', '3');
43 define('FRONTPAGECATEGORYCOMBO', '4');
44 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
45 define('EXCELROWS', 65535);
46 define('FIRSTUSEDEXCELROW', 3);
48 define('MOD_CLASS_ACTIVITY', 0);
49 define('MOD_CLASS_RESOURCE', 1);
51 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
52 define('MAX_MODINFO_CACHE_SIZE', 10);
55 function make_log_url($module, $url) {
56 switch ($module) {
57 case 'course':
58 case 'file':
59 case 'login':
60 case 'lib':
61 case 'admin':
62 case 'calendar':
63 case 'mnet course':
64 if (strpos($url, '../') === 0) {
65 $url = ltrim($url, '.');
66 } else {
67 $url = "/course/$url";
69 break;
70 case 'user':
71 case 'blog':
72 $url = "/$module/$url";
73 break;
74 case 'upload':
75 $url = $url;
76 break;
77 case 'coursetags':
78 $url = '/'.$url;
79 break;
80 case 'library':
81 case '':
82 $url = '/';
83 break;
84 case 'message':
85 $url = "/message/$url";
86 break;
87 case 'notes':
88 $url = "/notes/$url";
89 break;
90 case 'tag':
91 $url = "/tag/$url";
92 break;
93 case 'role':
94 $url = '/'.$url;
95 break;
96 default:
97 $url = "/mod/$module/$url";
98 break;
101 //now let's sanitise urls - there might be some ugly nasties:-(
102 $parts = explode('?', $url);
103 $script = array_shift($parts);
104 if (strpos($script, 'http') === 0) {
105 $script = clean_param($script, PARAM_URL);
106 } else {
107 $script = clean_param($script, PARAM_PATH);
110 $query = '';
111 if ($parts) {
112 $query = implode('', $parts);
113 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
114 $parts = explode('&', $query);
115 $eq = urlencode('=');
116 foreach ($parts as $key=>$part) {
117 $part = urlencode(urldecode($part));
118 $part = str_replace($eq, '=', $part);
119 $parts[$key] = $part;
121 $query = '?'.implode('&amp;', $parts);
124 return $script.$query;
128 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
129 $modname="", $modid=0, $modaction="", $groupid=0) {
130 global $CFG, $DB;
132 // It is assumed that $date is the GMT time of midnight for that day,
133 // and so the next 86400 seconds worth of logs are printed.
135 /// Setup for group handling.
137 // TODO: I don't understand group/context/etc. enough to be able to do
138 // something interesting with it here
139 // What is the context of a remote course?
141 /// If the group mode is separate, and this user does not have editing privileges,
142 /// then only the user's group can be viewed.
143 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
144 // $groupid = get_current_group($course->id);
146 /// If this course doesn't have groups, no groupid can be specified.
147 //else if (!$course->groupmode) {
148 // $groupid = 0;
151 $ILIKE = $DB->sql_ilike();
153 $groupid = 0;
155 $joins = array();
157 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
158 FROM {mnet_log} l
159 LEFT JOIN {user} u ON l.userid = u.id
160 WHERE ";
161 $params = array();
163 $where .= "l.hostid = :hostid";
164 $params['hostid'] = $hostid;
166 // TODO: Is 1 really a magic number referring to the sitename?
167 if ($course != SITEID || $modid != 0) {
168 $where .= " AND l.course=:courseid";
169 $params['courseid'] = $course;
172 if ($modname) {
173 $where .= " AND l.module = :modname";
174 $params['modname'] = $modname;
177 if ('site_errors' === $modid) {
178 $where .= " AND ( l.action='error' OR l.action='infected' )";
179 } else if ($modid) {
180 //TODO: This assumes that modids are the same across sites... probably
181 //not true
182 $where .= " AND l.cmid = :modid";
183 $params['modid'] = $modid;
186 if ($modaction) {
187 $firstletter = substr($modaction, 0, 1);
188 if (preg_match('/[[:alpha:]]/', $firstletter)) {
189 $where .= " AND lower(l.action) $ILIKE :modaction";
190 $params['modaction'] = "%$modaction%";
191 } else if ($firstletter == '-') {
192 $where .= " AND lower(l.action) NOT $ILIKE :modaction";
193 $params['modaction'] = "%$modaction%";
197 if ($user) {
198 $where .= " AND l.userid = :user";
199 $params['user'] = $user;
202 if ($date) {
203 $enddate = $date + 86400;
204 $where .= " AND l.time > :date AND l.time < :enddate";
205 $params['date'] = $date;
206 $params['enddate'] = $enddate;
209 $result = array();
210 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
211 if(!empty($result['totalcount'])) {
212 $where .= " ORDER BY $order";
213 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
214 } else {
215 $result['logs'] = array();
217 return $result;
220 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
221 $modname="", $modid=0, $modaction="", $groupid=0) {
222 global $DB, $SESSION;
223 // It is assumed that $date is the GMT time of midnight for that day,
224 // and so the next 86400 seconds worth of logs are printed.
226 /// Setup for group handling.
228 /// If the group mode is separate, and this user does not have editing privileges,
229 /// then only the user's group can be viewed.
230 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
231 if (isset($SESSION->currentgroup[$course->id])) {
232 $groupid = $SESSION->currentgroup[$course->id];
233 } else {
234 $groupid = groups_get_all_groups($course->id, $USER->id);
235 if (is_array($groupid)) {
236 $groupid = array_shift(array_keys($groupid));
237 $SESSION->currentgroup[$course->id] = $groupid;
238 } else {
239 $groupid = 0;
243 /// If this course doesn't have groups, no groupid can be specified.
244 else if (!$course->groupmode) {
245 $groupid = 0;
248 $joins = array();
249 $oarams = array();
251 if ($course->id != SITEID || $modid != 0) {
252 $joins[] = "l.course = :courseid";
253 $params['courseid'] = $course->id;
256 if ($modname) {
257 $joins[] = "l.module = :modname";
258 $params['modname'] = $modname;
261 if ('site_errors' === $modid) {
262 $joins[] = "( l.action='error' OR l.action='infected' )";
263 } else if ($modid) {
264 $joins[] = "l.cmid = :modid";
265 $params['modid'] = $modid;
268 if ($modaction) {
269 $ILIKE = $DB->sql_ilike();
270 $firstletter = substr($modaction, 0, 1);
271 if (preg_match('/[[:alpha:]]/', $firstletter)) {
272 $joins[] = "l.action $ILIKE :modaction";
273 $params['modaction'] = '%'.$modaction.'%';
274 } else if ($firstletter == '-') {
275 $joins[] = "l.action NOT $ILIKE :modaction";
276 $params['modaction'] = '%'.substr($modaction, 1).'%';
281 /// Getting all members of a group.
282 if ($groupid and !$user) {
283 if ($gusers = groups_get_members($groupid)) {
284 $gusers = array_keys($gusers);
285 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
286 } else {
287 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
290 else if ($user) {
291 $joins[] = "l.userid = :userid";
292 $params['userid'] = $user;
295 if ($date) {
296 $enddate = $date + 86400;
297 $joins[] = "l.time > :date AND l.time < :enddate";
298 $params['date'] = $date;
299 $params['enddate'] = $enddate;
302 $selector = implode(' AND ', $joins);
304 $totalcount = 0; // Initialise
305 $result = array();
306 $result['logs'] = get_logs($selector, $params, $order, $limitfrom, $limitnum, $totalcount);
307 $result['totalcount'] = $totalcount;
308 return $result;
312 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
313 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
315 global $CFG, $DB, $OUTPUT;
317 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
318 $modname, $modid, $modaction, $groupid)) {
319 echo $OUTPUT->notification("No logs found!");
320 echo $OUTPUT->footer();
321 exit;
324 $courses = array();
326 if ($course->id == SITEID) {
327 $courses[0] = '';
328 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
329 foreach ($ccc as $cc) {
330 $courses[$cc->id] = $cc->shortname;
333 } else {
334 $courses[$course->id] = $course->shortname;
337 $totalcount = $logs['totalcount'];
338 $count=0;
339 $ldcache = array();
340 $tt = getdate(time());
341 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
343 $strftimedatetime = get_string("strftimedatetime");
345 echo "<div class=\"info\">\n";
346 print_string("displayingrecords", "", $totalcount);
347 echo "</div>\n";
349 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
351 $table = new html_table();
352 $table->classes = array('logtable','generalbox');
353 $table->align = array('right', 'left', 'left');
354 $table->head = array(
355 get_string('time'),
356 get_string('ip_address'),
357 get_string('fullnamecourse'),
358 get_string('action'),
359 get_string('info')
361 $table->data = array();
363 if ($course->id == SITEID) {
364 array_unshift($table->align, 'left');
365 array_unshift($table->head, get_string('course'));
368 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
369 if (empty($logs['logs'])) {
370 $logs['logs'] = array();
373 foreach ($logs['logs'] as $log) {
375 if (isset($ldcache[$log->module][$log->action])) {
376 $ld = $ldcache[$log->module][$log->action];
377 } else {
378 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
379 $ldcache[$log->module][$log->action] = $ld;
381 if ($ld && is_numeric($log->info)) {
382 // ugly hack to make sure fullname is shown correctly
383 if ($ld->mtable == 'user' && $ld->field == $DB->sql_concat('firstname', "' '" , 'lastname')) {
384 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
385 } else {
386 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
390 //Filter log->info
391 $log->info = format_string($log->info);
393 // If $log->url has been trimmed short by the db size restriction
394 // code in add_to_log, keep a note so we don't add a link to a broken url
395 $tl=textlib_get_instance();
396 $brokenurl=($tl->strlen($log->url)==100 && $tl->substr($log->url,97)=='...');
398 $row = array();
399 if ($course->id == SITEID) {
400 if (empty($log->course)) {
401 $row[] = get_string('site');
402 } else {
403 $row[] = "<a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>";
407 $row[] = userdate($log->time, '%a').' '.userdate($log->time, $strftimedatetime);
409 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
410 $row[] = $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 440, 'width' => 700)));
412 $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))));
414 $displayaction="$log->module $log->action";
415 if ($brokenurl) {
416 $row[] = $displayaction;
417 } else {
418 $link = make_log_url($log->module,$log->url);
419 $row[] = $OUTPUT->action_link($link, $displayaction, new popup_action('click', $link, 'fromloglive'), array('height' => 440, 'width' => 700));
421 $row[] = $log->info;
422 $table->data[] = $row;
425 echo html_writer::table($table);
426 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
430 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
431 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
433 global $CFG, $DB, $OUTPUT;
435 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
436 $modname, $modid, $modaction, $groupid)) {
437 echo $OUTPUT->notification("No logs found!");
438 echo $OUTPUT->footer();
439 exit;
442 if ($course->id == SITEID) {
443 $courses[0] = '';
444 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
445 foreach ($ccc as $cc) {
446 $courses[$cc->id] = $cc->shortname;
451 $totalcount = $logs['totalcount'];
452 $count=0;
453 $ldcache = array();
454 $tt = getdate(time());
455 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
457 $strftimedatetime = get_string("strftimedatetime");
459 echo "<div class=\"info\">\n";
460 print_string("displayingrecords", "", $totalcount);
461 echo "</div>\n";
463 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
465 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
466 echo "<tr>";
467 if ($course->id == SITEID) {
468 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
470 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
471 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
472 echo "<th class=\"c3 header\">".get_string('fullnamecourse')."</th>\n";
473 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
474 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
475 echo "</tr>\n";
477 if (empty($logs['logs'])) {
478 echo "</table>\n";
479 return;
482 $row = 1;
483 foreach ($logs['logs'] as $log) {
485 $log->info = $log->coursename;
486 $row = ($row + 1) % 2;
488 if (isset($ldcache[$log->module][$log->action])) {
489 $ld = $ldcache[$log->module][$log->action];
490 } else {
491 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
492 $ldcache[$log->module][$log->action] = $ld;
494 if (0 && $ld && !empty($log->info)) {
495 // ugly hack to make sure fullname is shown correctly
496 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
497 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
498 } else {
499 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
503 //Filter log->info
504 $log->info = format_string($log->info);
506 echo '<tr class="r'.$row.'">';
507 if ($course->id == SITEID) {
508 echo "<td class=\"r$row c0\" >\n";
509 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
510 echo "</td>\n";
512 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
513 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
514 echo "<td class=\"r$row c2\" >\n";
515 $link = new moodle_url("/iplookup/index.php?ip=$log->ip&user=$log->userid");
516 echo $OUTPUT->action_link($link, $log->ip, new popup_action('click', $link, 'iplookup', array('height' => 400, 'width' => 700)));
517 echo "</td>\n";
518 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
519 echo "<td class=\"r$row c3\" >\n";
520 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
521 echo "</td>\n";
522 echo "<td class=\"r$row c4\">\n";
523 echo $log->action .': '.$log->module;
524 echo "</td>\n";;
525 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
526 echo "</tr>\n";
528 echo "</table>\n";
530 echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage");
534 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
535 $modid, $modaction, $groupid) {
536 global $DB;
538 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
539 get_string('fullnamecourse')."\t".get_string('action')."\t".get_string('info');
541 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
542 $modname, $modid, $modaction, $groupid)) {
543 return false;
546 $courses = array();
548 if ($course->id == SITEID) {
549 $courses[0] = '';
550 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
551 foreach ($ccc as $cc) {
552 $courses[$cc->id] = $cc->shortname;
555 } else {
556 $courses[$course->id] = $course->shortname;
559 $count=0;
560 $ldcache = array();
561 $tt = getdate(time());
562 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
564 $strftimedatetime = get_string("strftimedatetime");
566 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
567 $filename .= '.txt';
568 header("Content-Type: application/download\n");
569 header("Content-Disposition: attachment; filename=$filename");
570 header("Expires: 0");
571 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
572 header("Pragma: public");
574 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
575 echo $text;
577 if (empty($logs['logs'])) {
578 return true;
581 foreach ($logs['logs'] as $log) {
582 if (isset($ldcache[$log->module][$log->action])) {
583 $ld = $ldcache[$log->module][$log->action];
584 } else {
585 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
586 $ldcache[$log->module][$log->action] = $ld;
588 if ($ld && !empty($log->info)) {
589 // ugly hack to make sure fullname is shown correctly
590 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
591 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
592 } else {
593 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
597 //Filter log->info
598 $log->info = format_string($log->info);
599 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
601 $firstField = $courses[$log->course];
602 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
603 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
604 $text = implode("\t", $row);
605 echo $text." \n";
607 return true;
611 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
612 $modid, $modaction, $groupid) {
614 global $CFG, $DB;
616 require_once("$CFG->libdir/excellib.class.php");
618 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
619 $modname, $modid, $modaction, $groupid)) {
620 return false;
623 $courses = array();
625 if ($course->id == SITEID) {
626 $courses[0] = '';
627 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
628 foreach ($ccc as $cc) {
629 $courses[$cc->id] = $cc->shortname;
632 } else {
633 $courses[$course->id] = $course->shortname;
636 $count=0;
637 $ldcache = array();
638 $tt = getdate(time());
639 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
641 $strftimedatetime = get_string("strftimedatetime");
643 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
644 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
645 $filename .= '.xls';
647 $workbook = new MoodleExcelWorkbook('-');
648 $workbook->send($filename);
650 $worksheet = array();
651 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
652 get_string('fullnamecourse'), get_string('action'), get_string('info'));
654 // Creating worksheets
655 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
656 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
657 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
658 $worksheet[$wsnumber]->set_column(1, 1, 30);
659 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
660 userdate(time(), $strftimedatetime));
661 $col = 0;
662 foreach ($headers as $item) {
663 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
664 $col++;
668 if (empty($logs['logs'])) {
669 $workbook->close();
670 return true;
673 $formatDate =& $workbook->add_format();
674 $formatDate->set_num_format(get_string('log_excel_date_format'));
676 $row = FIRSTUSEDEXCELROW;
677 $wsnumber = 1;
678 $myxls =& $worksheet[$wsnumber];
679 foreach ($logs['logs'] as $log) {
680 if (isset($ldcache[$log->module][$log->action])) {
681 $ld = $ldcache[$log->module][$log->action];
682 } else {
683 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
684 $ldcache[$log->module][$log->action] = $ld;
686 if ($ld && !empty($log->info)) {
687 // ugly hack to make sure fullname is shown correctly
688 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
689 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
690 } else {
691 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
695 // Filter log->info
696 $log->info = format_string($log->info);
697 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
699 if ($nroPages>1) {
700 if ($row > EXCELROWS) {
701 $wsnumber++;
702 $myxls =& $worksheet[$wsnumber];
703 $row = FIRSTUSEDEXCELROW;
707 $myxls->write($row, 0, $courses[$log->course], '');
708 $myxls->write_date($row, 1, $log->time, $formatDate); // write_date() does conversion/timezone support. MDL-14934
709 $myxls->write($row, 2, $log->ip, '');
710 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
711 $myxls->write($row, 3, $fullname, '');
712 $myxls->write($row, 4, $log->module.' '.$log->action, '');
713 $myxls->write($row, 5, $log->info, '');
715 $row++;
718 $workbook->close();
719 return true;
722 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
723 $modid, $modaction, $groupid) {
725 global $CFG, $DB;
727 require_once("$CFG->libdir/odslib.class.php");
729 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
730 $modname, $modid, $modaction, $groupid)) {
731 return false;
734 $courses = array();
736 if ($course->id == SITEID) {
737 $courses[0] = '';
738 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
739 foreach ($ccc as $cc) {
740 $courses[$cc->id] = $cc->shortname;
743 } else {
744 $courses[$course->id] = $course->shortname;
747 $count=0;
748 $ldcache = array();
749 $tt = getdate(time());
750 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
752 $strftimedatetime = get_string("strftimedatetime");
754 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
755 $filename = 'logs_'.userdate(time(),get_string('backupnameformat', 'langconfig'),99,false);
756 $filename .= '.ods';
758 $workbook = new MoodleODSWorkbook('-');
759 $workbook->send($filename);
761 $worksheet = array();
762 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
763 get_string('fullnamecourse'), get_string('action'), get_string('info'));
765 // Creating worksheets
766 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
767 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
768 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
769 $worksheet[$wsnumber]->set_column(1, 1, 30);
770 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
771 userdate(time(), $strftimedatetime));
772 $col = 0;
773 foreach ($headers as $item) {
774 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
775 $col++;
779 if (empty($logs['logs'])) {
780 $workbook->close();
781 return true;
784 $formatDate =& $workbook->add_format();
785 $formatDate->set_num_format(get_string('log_excel_date_format'));
787 $row = FIRSTUSEDEXCELROW;
788 $wsnumber = 1;
789 $myxls =& $worksheet[$wsnumber];
790 foreach ($logs['logs'] as $log) {
791 if (isset($ldcache[$log->module][$log->action])) {
792 $ld = $ldcache[$log->module][$log->action];
793 } else {
794 $ld = $DB->get_record('log_display', array('module'=>$log->module, 'action'=>$log->action));
795 $ldcache[$log->module][$log->action] = $ld;
797 if ($ld && !empty($log->info)) {
798 // ugly hack to make sure fullname is shown correctly
799 if (($ld->mtable == 'user') and ($ld->field == $DB->sql_concat('firstname', "' '" , 'lastname'))) {
800 $log->info = fullname($DB->get_record($ld->mtable, array('id'=>$log->info)), true);
801 } else {
802 $log->info = $DB->get_field($ld->mtable, $ld->field, array('id'=>$log->info));
806 // Filter log->info
807 $log->info = format_string($log->info);
808 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
810 if ($nroPages>1) {
811 if ($row > EXCELROWS) {
812 $wsnumber++;
813 $myxls =& $worksheet[$wsnumber];
814 $row = FIRSTUSEDEXCELROW;
818 $myxls->write_string($row, 0, $courses[$log->course]);
819 $myxls->write_date($row, 1, $log->time);
820 $myxls->write_string($row, 2, $log->ip);
821 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
822 $myxls->write_string($row, 3, $fullname);
823 $myxls->write_string($row, 4, $log->module.' '.$log->action);
824 $myxls->write_string($row, 5, $log->info);
826 $row++;
829 $workbook->close();
830 return true;
834 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
835 global $CFG, $USER;
836 if (empty($CFG->gdversion)) {
837 echo "(".get_string("gdneed").")";
838 } else {
839 // MDL-10818, do not display broken graph when user has no permission to view graph
840 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id)) ||
841 ($course->showreports and $USER->id == $userid)) {
842 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
843 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
849 function print_overview($courses) {
850 global $CFG, $USER, $DB, $OUTPUT;
852 $htmlarray = array();
853 if ($modules = $DB->get_records('modules')) {
854 foreach ($modules as $mod) {
855 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
856 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
857 $fname = $mod->name.'_print_overview';
858 if (function_exists($fname)) {
859 $fname($courses,$htmlarray);
864 foreach ($courses as $course) {
865 echo $OUTPUT->box_start("coursebox");
866 $linkcss = '';
867 if (empty($course->visible)) {
868 $linkcss = 'class="dimmed"';
870 echo $OUTPUT->heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>', 3);
871 if (array_key_exists($course->id,$htmlarray)) {
872 foreach ($htmlarray[$course->id] as $modname => $html) {
873 echo $html;
876 echo $OUTPUT->box_end();
882 * This function trawls through the logs looking for
883 * anything new since the user's last login
885 function print_recent_activity($course) {
886 // $course is an object
887 global $CFG, $USER, $SESSION, $DB, $OUTPUT;
889 $context = get_context_instance(CONTEXT_COURSE, $course->id);
891 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
893 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
895 if (!isguestuser()) {
896 if (!empty($USER->lastcourseaccess[$course->id])) {
897 if ($USER->lastcourseaccess[$course->id] > $timestart) {
898 $timestart = $USER->lastcourseaccess[$course->id];
903 echo '<div class="activitydate">';
904 echo get_string('activitysince', '', userdate($timestart));
905 echo '</div>';
906 echo '<div class="activityhead">';
908 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
910 echo "</div>\n";
912 $content = false;
914 /// Firstly, have there been any new enrolments?
916 $users = get_recent_enrolments($course->id, $timestart);
918 //Accessibility: new users now appear in an <OL> list.
919 if ($users) {
920 echo '<div class="newusers">';
921 echo $OUTPUT->heading(get_string("newusers").':', 3);
922 $content = true;
923 echo "<ol class=\"list\">\n";
924 foreach ($users as $user) {
925 $fullname = fullname($user, $viewfullnames);
926 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
928 echo "</ol>\n</div>\n";
931 /// Next, have there been any modifications to the course structure?
933 $modinfo =& get_fast_modinfo($course);
935 $changelist = array();
937 $logs = $DB->get_records_select('log', "time > ? AND course = ? AND
938 module = 'course' AND
939 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
940 array($timestart, $course->id), "id ASC");
942 if ($logs) {
943 $actions = array('add mod', 'update mod', 'delete mod');
944 $newgones = array(); // added and later deleted items
945 foreach ($logs as $key => $log) {
946 if (!in_array($log->action, $actions)) {
947 continue;
949 $info = split(' ', $log->info);
951 if ($info[0] == 'label') { // Labels are ignored in recent activity
952 continue;
955 if (count($info) != 2) {
956 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
957 continue;
960 $modname = $info[0];
961 $instanceid = $info[1];
963 if ($log->action == 'delete mod') {
964 // unfortunately we do not know if the mod was visible
965 if (!array_key_exists($log->info, $newgones)) {
966 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
967 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
969 } else {
970 if (!isset($modinfo->instances[$modname][$instanceid])) {
971 if ($log->action == 'add mod') {
972 // do not display added and later deleted activities
973 $newgones[$log->info] = true;
975 continue;
977 $cm = $modinfo->instances[$modname][$instanceid];
978 if (!$cm->uservisible) {
979 continue;
982 if ($log->action == 'add mod') {
983 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
984 $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>");
986 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
987 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
988 $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>");
994 if (!empty($changelist)) {
995 echo $OUTPUT->heading(get_string("courseupdates").':', 3);
996 $content = true;
997 foreach ($changelist as $changeinfo => $change) {
998 echo '<p class="activity">'.$change['text'].'</p>';
1002 /// Now display new things from each module
1004 $usedmodules = array();
1005 foreach($modinfo->cms as $cm) {
1006 if (isset($usedmodules[$cm->modname])) {
1007 continue;
1009 if (!$cm->uservisible) {
1010 continue;
1012 $usedmodules[$cm->modname] = $cm->modname;
1015 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
1016 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
1017 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
1018 $print_recent_activity = $modname.'_print_recent_activity';
1019 if (function_exists($print_recent_activity)) {
1020 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
1021 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
1023 } else {
1024 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
1028 if (! $content) {
1029 echo '<p class="message">'.get_string('nothingnew').'</p>';
1034 * For a given course, returns an array of course activity objects
1035 * Each item in the array contains he following properties:
1037 function get_array_of_activities($courseid) {
1038 // cm - course module id
1039 // mod - name of the module (eg forum)
1040 // section - the number of the section (eg week or topic)
1041 // name - the name of the instance
1042 // visible - is the instance visible or not
1043 // groupingid - grouping id
1044 // groupmembersonly - is this instance visible to group members only
1045 // extra - contains extra string to include in any link
1046 global $CFG, $DB;
1047 if(!empty($CFG->enableavailability)) {
1048 require_once($CFG->libdir.'/conditionlib.php');
1051 $course = $DB->get_record('course', array('id'=>$courseid));
1053 if (empty($course)) {
1054 throw new moodle_exception('courseidnotfound');
1057 $mod = array();
1059 $rawmods = get_course_mods($courseid);
1060 if (empty($rawmods)) {
1061 return $mod; // always return array
1064 if ($sections = $DB->get_records("course_sections", array("course"=>$courseid), "section ASC")) {
1065 foreach ($sections as $section) {
1066 if (!empty($section->sequence)) {
1067 $sequence = explode(",", $section->sequence);
1068 foreach ($sequence as $seq) {
1069 if (empty($rawmods[$seq])) {
1070 continue;
1072 $mod[$seq]->id = $rawmods[$seq]->instance;
1073 $mod[$seq]->cm = $rawmods[$seq]->id;
1074 $mod[$seq]->mod = $rawmods[$seq]->modname;
1075 $mod[$seq]->section = $section->section;
1076 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
1077 $mod[$seq]->visible = $rawmods[$seq]->visible;
1078 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
1079 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
1080 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
1081 $mod[$seq]->indent = $rawmods[$seq]->indent;
1082 $mod[$seq]->completion = $rawmods[$seq]->completion;
1083 $mod[$seq]->extra = "";
1084 if(!empty($CFG->enableavailability)) {
1085 condition_info::fill_availability_conditions($rawmods[$seq]);
1086 $mod[$seq]->availablefrom = $rawmods[$seq]->availablefrom;
1087 $mod[$seq]->availableuntil = $rawmods[$seq]->availableuntil;
1088 $mod[$seq]->showavailability = $rawmods[$seq]->showavailability;
1089 $mod[$seq]->conditionscompletion = $rawmods[$seq]->conditionscompletion;
1090 $mod[$seq]->conditionsgrade = $rawmods[$seq]->conditionsgrade;
1093 $modname = $mod[$seq]->mod;
1094 $functionname = $modname."_get_coursemodule_info";
1096 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1097 continue;
1100 include_once("$CFG->dirroot/mod/$modname/lib.php");
1102 if (function_exists($functionname)) {
1103 if ($info = $functionname($rawmods[$seq])) {
1104 if (!empty($info->extra)) {
1105 $mod[$seq]->extra = $info->extra;
1107 if (!empty($info->icon)) {
1108 $mod[$seq]->icon = $info->icon;
1110 if (!empty($info->iconcomponent)) {
1111 $mod[$seq]->iconcomponent = $info->iconcomponent;
1113 if (!empty($info->name)) {
1114 $mod[$seq]->name = $info->name;
1118 if (!isset($mod[$seq]->name)) {
1119 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1125 return $mod;
1130 * Returns a number of useful structures for course displays
1132 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1133 global $CFG, $DB, $COURSE;
1135 $mods = array(); // course modules indexed by id
1136 $modnames = array(); // all course module names (except resource!)
1137 $modnamesplural= array(); // all course module names (plural form)
1138 $modnamesused = array(); // course module names used
1140 if ($allmods = $DB->get_records("modules")) {
1141 foreach ($allmods as $mod) {
1142 if (!file_exists("$CFG->dirroot/mod/$mod->name/lib.php")) {
1143 continue;
1145 if ($mod->visible) {
1146 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1147 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1150 asort($modnames, SORT_LOCALE_STRING);
1151 } else {
1152 print_error("nomodules", 'debug');
1155 $course = ($courseid==$COURSE->id) ? $COURSE : $DB->get_record('course',array('id'=>$courseid));
1156 $modinfo = get_fast_modinfo($course);
1158 if ($rawmods=$modinfo->cms) {
1159 foreach($rawmods as $mod) { // Index the mods
1160 if (empty($modnames[$mod->modname])) {
1161 continue;
1163 $mods[$mod->id] = $mod;
1164 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1165 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1166 continue;
1168 // Check groupings
1169 if (!groups_course_module_visible($mod)) {
1170 continue;
1172 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1174 if ($modnamesused) {
1175 asort($modnamesused, SORT_LOCALE_STRING);
1181 * Returns an array of sections for the requested course id
1183 * This function stores the sections against the course id within a staticvar encase
1184 * of subsequent requests. This is used all over + in some standard libs and course
1185 * format callbacks so subsequent requests are a reality.
1187 * @staticvar array $coursesections
1188 * @param int $courseid
1189 * @return array Array of sections
1191 function get_all_sections($courseid) {
1192 global $DB;
1193 static $coursesections = array();
1194 if (!array_key_exists($courseid, $coursesections)) {
1195 $coursesections[$courseid] = $DB->get_records("course_sections", array("course"=>"$courseid"), "section",
1196 "section, id, course, name, summary, summaryformat, sequence, visible");
1198 return $coursesections[$courseid];
1201 function course_set_display($courseid, $display=0) {
1202 global $USER, $DB;
1204 if ($display == "all" or empty($display)) {
1205 $display = 0;
1208 if (!isloggedin() or isguestuser()) {
1209 //do not store settings in db for guests
1210 } else if ($DB->record_exists("course_display", array("userid" => $USER->id, "course"=>$courseid))) {
1211 $DB->set_field("course_display", "display", $display, array("userid"=>$USER->id, "course"=>$courseid));
1212 } else {
1213 $record = new object();
1214 $record->userid = $USER->id;
1215 $record->course = $courseid;
1216 $record->display = $display;
1217 $DB->insert_record("course_display", $record);
1220 return $USER->display[$courseid] = $display; // Note: = not ==
1224 * For a given course section, markes it visible or hidden,
1225 * and does the same for every activity in that section
1227 function set_section_visible($courseid, $sectionnumber, $visibility) {
1228 global $DB;
1230 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
1231 $DB->set_field("course_sections", "visible", "$visibility", array("id"=>$section->id));
1232 if (!empty($section->sequence)) {
1233 $modules = explode(",", $section->sequence);
1234 foreach ($modules as $moduleid) {
1235 set_coursemodule_visible($moduleid, $visibility, true);
1238 rebuild_course_cache($courseid);
1243 * Prints a section full of activity modules
1245 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%", $hidecompletion=false) {
1246 global $CFG, $USER, $DB, $PAGE, $OUTPUT;
1248 static $initialised;
1250 static $groupbuttons;
1251 static $groupbuttonslink;
1252 static $isediting;
1253 static $ismoving;
1254 static $strmovehere;
1255 static $strmovefull;
1256 static $strunreadpostsone;
1257 static $usetracking;
1258 static $groupings;
1260 if (!isset($initialised)) {
1261 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1262 $groupbuttonslink = (!$course->groupmodeforce);
1263 $isediting = $PAGE->user_is_editing();
1264 $ismoving = $isediting && ismoving($course->id);
1265 if ($ismoving) {
1266 $strmovehere = get_string("movehere");
1267 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1269 include_once($CFG->dirroot.'/mod/forum/lib.php');
1270 if ($usetracking = forum_tp_can_track_forums()) {
1271 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1273 $initialised = true;
1276 $labelformatoptions = new object();
1277 $labelformatoptions->noclean = true;
1279 /// Casting $course->modinfo to string prevents one notice when the field is null
1280 $modinfo = get_fast_modinfo($course);
1281 $completioninfo = new completion_info($course);
1283 //Acccessibility: replace table with list <ul>, but don't output empty list.
1284 if (!empty($section->sequence)) {
1286 // Fix bug #5027, don't want style=\"width:$width\".
1287 echo "<ul class=\"section img-text\">\n";
1288 $sectionmods = explode(",", $section->sequence);
1290 foreach ($sectionmods as $modnumber) {
1291 if (empty($mods[$modnumber])) {
1292 continue;
1295 $mod = $mods[$modnumber];
1297 if ($ismoving and $mod->id == $USER->activitycopy) {
1298 // do not display moving mod
1299 continue;
1302 if (isset($modinfo->cms[$modnumber])) {
1303 // We can continue (because it will not be displayed at all)
1304 // if:
1305 // 1) The activity is not visible to users
1306 // and
1307 // 2a) The 'showavailability' option is not set (if that is set,
1308 // we need to display the activity so we can show
1309 // availability info)
1310 // or
1311 // 2b) The 'availableinfo' is empty, i.e. the activity was
1312 // hidden in a way that leaves no info, such as using the
1313 // eye icon.
1314 if (!$modinfo->cms[$modnumber]->uservisible &&
1315 (empty($modinfo->cms[$modnumber]->showavailability) ||
1316 empty($modinfo->cms[$modnumber]->availableinfo))) {
1317 // visibility shortcut
1318 continue;
1320 } else {
1321 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1322 // module not installed
1323 continue;
1325 if (!coursemodule_visible_for_user($mod) &&
1326 empty($mod->showavailability)) {
1327 // full visibility check
1328 continue;
1332 // In some cases the activity is visible to user, but it is
1333 // dimmed. This is done if viewhiddenactivities is true and if:
1334 // 1. the activity is not visible, or
1335 // 2. the activity has dates set which do not include current, or
1336 // 3. the activity has any other conditions set (regardless of whether
1337 // current user meets them)
1338 $canviewhidden = has_capability(
1339 'moodle/course:viewhiddenactivities',
1340 get_context_instance(CONTEXT_MODULE, $mod->id));
1341 $accessiblebutdim = false;
1342 if ($canviewhidden) {
1343 $accessiblebutdim = !$mod->visible;
1344 if (!empty($CFG->enableavailability)) {
1345 $accessiblebutdim = $accessiblebutdim ||
1346 $mod->availablefrom > time() ||
1347 ($mod->availableuntil && $mod->availableuntil < time()) ||
1348 count($mod->conditionsgrade) > 0 ||
1349 count($mod->conditionscompletion) > 0;
1353 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1354 if ($ismoving) {
1355 echo '<a title="'.$strmovefull.'"'.
1356 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.sesskey().'">'.
1357 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1358 ' alt="'.$strmovehere.'" /></a><br />
1362 if ($mod->indent) {
1363 echo $OUTPUT->spacer(array('height'=>12, 'width'=>(20 * $mod->indent))); // should be done with CSS instead
1366 $extra = '';
1367 if (!empty($modinfo->cms[$modnumber]->extra)) {
1368 $extra = $modinfo->cms[$modnumber]->extra;
1371 if ($mod->modname == "label") {
1372 if ($accessiblebutdim || !$mod->uservisible) {
1373 echo '<div class="dimmed_text"><span class="accesshide">'.
1374 get_string('hiddenfromstudents').'</span>';
1375 } else {
1376 echo '<div>';
1378 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1379 echo "</div>";
1380 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1381 if (!isset($groupings)) {
1382 $groupings = groups_get_all_groupings($course->id);
1384 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1387 } else { // Normal activity
1388 $instancename = format_string($modinfo->cms[$modnumber]->name, true, $course->id);
1390 $customicon = $modinfo->cms[$modnumber]->icon;
1391 if (!empty($customicon)) {
1392 if (substr($customicon, 0, 4) === 'mod/') {
1393 list($modname, $iconname) = explode('/', substr($customicon, 4), 2);
1394 $icon = $OUTPUT->pix_url(str_replace(array('.gif', '.png'), '', $customicon), $modname);
1395 } else {
1396 $icon = $OUTPUT->pix_url(str_replace(array('.gif', '.png'), '', $customicon));
1398 } else {
1399 $icon = $OUTPUT->pix_url('icon', $mod->modname);
1402 //Accessibility: for files get description via icon, this is very ugly hack!
1403 $altname = '';
1404 $altname = $mod->modfullname;
1405 if (!empty($customicon)) {
1406 $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1407 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1408 $possaltname = str_replace(array('.gif', '.png'), '', $customicon).'.gif';
1410 $mimetype = mimeinfo_from_icon('type', $possaltname);
1411 $altname = get_mimetype_description($mimetype);
1414 // Avoid unnecessary duplication.
1415 if (false !== stripos($instancename, $altname)) {
1416 $altname = '';
1418 // File type after name, for alphabetic lists (screen reader).
1419 if ($altname) {
1420 $altname = get_accesshide(' '.$altname);
1423 // We may be displaying this just in order to show information
1424 // about visibility, without the actual link
1425 if ($mod->uservisible) {
1426 // Display normal module link
1427 if (!$accessiblebutdim) {
1428 $linkcss = '';
1429 $accesstext ='';
1430 } else {
1431 $linkcss = ' class="dimmed" ';
1432 $accesstext = '<span class="accesshide">'.
1433 get_string('hiddenfromstudents').': </span>';
1436 echo '<a '.$linkcss.' '.$extra.
1437 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1438 '<img src="'.$icon.'" class="activityicon" alt="" /> '.
1439 $accesstext.'<span>'.$instancename.$altname.'</span></a>';
1441 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1442 if (!isset($groupings)) {
1443 $groupings = groups_get_all_groupings($course->id);
1445 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1447 } else {
1448 // Display greyed-out text of link
1449 echo '<span class="dimmed_text" '.$extra.' ><span class="accesshide">'.
1450 get_string('notavailableyet','condition').': </span>'.
1451 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1452 $instancename.$altname.'</span></span>';
1455 if ($usetracking && $mod->modname == 'forum') {
1456 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1457 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1458 if ($unread == 1) {
1459 echo $strunreadpostsone;
1460 } else {
1461 print_string('unreadpostsnumber', 'forum', $unread);
1463 echo '</a></span>';
1467 if ($isediting) {
1468 // TODO: we must define this as mod property!
1469 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1470 if (! $mod->groupmodelink = $groupbuttonslink) {
1471 $mod->groupmode = $course->groupmode;
1474 } else {
1475 $mod->groupmode = false;
1477 echo '&nbsp;&nbsp;';
1478 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1481 // Completion
1482 $completion = $hidecompletion
1483 ? COMPLETION_TRACKING_NONE
1484 : $completioninfo->is_enabled($mod);
1485 if ($completion!=COMPLETION_TRACKING_NONE && isloggedin() &&
1486 !isguestuser() && $mod->uservisible) {
1487 $completiondata = $completioninfo->get_data($mod,true);
1488 $completionicon = '';
1489 if ($isediting) {
1490 switch ($completion) {
1491 case COMPLETION_TRACKING_MANUAL :
1492 $completionicon = 'manual-enabled'; break;
1493 case COMPLETION_TRACKING_AUTOMATIC :
1494 $completionicon = 'auto-enabled'; break;
1495 default: // wtf
1497 } else if ($completion==COMPLETION_TRACKING_MANUAL) {
1498 switch($completiondata->completionstate) {
1499 case COMPLETION_INCOMPLETE:
1500 $completionicon = 'manual-n'; break;
1501 case COMPLETION_COMPLETE:
1502 $completionicon = 'manual-y'; break;
1504 } else { // Automatic
1505 switch($completiondata->completionstate) {
1506 case COMPLETION_INCOMPLETE:
1507 $completionicon = 'auto-n'; break;
1508 case COMPLETION_COMPLETE:
1509 $completionicon = 'auto-y'; break;
1510 case COMPLETION_COMPLETE_PASS:
1511 $completionicon = 'auto-pass'; break;
1512 case COMPLETION_COMPLETE_FAIL:
1513 $completionicon = 'auto-fail'; break;
1516 if ($completionicon) {
1517 $imgsrc = $OUTPUT->pix_url('i/completion-'.$completionicon);
1518 $imgalt = s(get_string('completion-alt-'.$completionicon, 'completion'));
1519 if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) {
1520 $imgtitle = s(get_string('completion-title-'.$completionicon, 'completion'));
1521 $newstate =
1522 $completiondata->completionstate==COMPLETION_COMPLETE
1523 ? COMPLETION_INCOMPLETE
1524 : COMPLETION_COMPLETE;
1525 // In manual mode the icon is a toggle form...
1527 // If this completion state is used by the
1528 // conditional activities system, we need to turn
1529 // off the JS.
1530 if (!empty($CFG->enableavailability) &&
1531 condition_info::completion_value_used_as_condition($course, $mod)) {
1532 $extraclass = ' preventjs';
1533 } else {
1534 $extraclass = '';
1536 echo "
1537 <form class='togglecompletion$extraclass' method='post' action='togglecompletion.php'><div>
1538 <input type='hidden' name='id' value='{$mod->id}' />
1539 <input type='hidden' name='sesskey' value='".sesskey()."' />
1540 <input type='hidden' name='completionstate' value='$newstate' />
1541 <input type='image' src='$imgsrc' alt='$imgalt' title='$imgtitle' />
1542 </div></form>";
1543 } else {
1544 // In auto mode, or when editing, the icon is just an image
1545 echo "<span class='autocompletion'>";
1546 echo "<img src='$imgsrc' alt='$imgalt' title='$imgalt' /></span>";
1551 // Show availability information (for someone who isn't allowed to
1552 // see the activity itself, or for staff)
1553 if (!$mod->uservisible) {
1554 echo '<div class="availabilityinfo">'.$mod->availableinfo.'</div>';
1555 } else if ($canviewhidden && !empty($CFG->enableavailability)) {
1556 $ci = new condition_info($mod);
1557 $fullinfo = $ci->get_full_information();
1558 if($fullinfo) {
1559 echo '<div class="availabilityinfo">'.get_string($mod->showavailability
1560 ? 'userrestriction_visible'
1561 : 'userrestriction_hidden','condition',
1562 $fullinfo).'</div>';
1566 echo "</li>\n";
1569 } elseif ($ismoving) {
1570 echo "<ul class=\"section\">\n";
1573 if ($ismoving) {
1574 echo '<li><a title="'.$strmovefull.'"'.
1575 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.sesskey().'">'.
1576 '<img class="movetarget" src="'.$OUTPUT->pix_url('movehere') . '" '.
1577 ' alt="'.$strmovehere.'" /></a></li>
1580 if (!empty($section->sequence) || $ismoving) {
1581 echo "</ul><!--class='section'-->\n\n";
1586 * Prints the menus to add activities and resources.
1588 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1589 global $CFG, $OUTPUT;
1591 // check to see if user can add menus
1592 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1593 return false;
1596 $urlbase = "/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey().'&add=';
1598 $resources = array();
1599 $activities = array();
1601 foreach($modnames as $modname=>$modnamestr) {
1602 if (!course_allowed_module($course, $modname)) {
1603 continue;
1606 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1607 if (!file_exists($libfile)) {
1608 continue;
1610 include_once($libfile);
1611 $gettypesfunc = $modname.'_get_types';
1612 if (function_exists($gettypesfunc)) {
1613 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
1614 if ($types = $gettypesfunc()) {
1615 $menu = array();
1616 $atype = null;
1617 $groupname = null;
1618 foreach($types as $type) {
1619 if ($type->typestr === '--') {
1620 continue;
1622 if (strpos($type->typestr, '--') === 0) {
1623 $groupname = str_replace('--', '', $type->typestr);
1624 continue;
1626 $type->type = str_replace('&amp;', '&', $type->type);
1627 if ($type->modclass == MOD_CLASS_RESOURCE) {
1628 $atype = MOD_CLASS_RESOURCE;
1630 $menu[$urlbase.$type->type] = $type->typestr;
1632 if (!is_null($groupname)) {
1633 if ($atype == MOD_CLASS_RESOURCE) {
1634 $resources[] = array($groupname=>$menu);
1635 } else {
1636 $activities[] = array($groupname=>$menu);
1638 } else {
1639 if ($atype == MOD_CLASS_RESOURCE) {
1640 $resources = array_merge($resources, $menu);
1641 } else {
1642 $activities = array_merge($activities, $menu);
1646 } else {
1647 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1648 if ($archetype == MOD_ARCHETYPE_RESOURCE) {
1649 $resources[$urlbase.$modname] = $modnamestr;
1650 } else {
1651 // all other archetypes are considered activity
1652 $activities[$urlbase.$modname] = $modnamestr;
1657 $straddactivity = get_string('addactivity');
1658 $straddresource = get_string('addresource');
1660 $output = '<div class="section_add_menus">';
1662 if (!$vertical) {
1663 $output .= '<div class="horizontal">';
1666 if (!empty($resources)) {
1667 $select = new url_select($resources, '', array(''=>$straddresource), "ressection$section");
1668 $select->set_help_icon('resources');
1669 $output .= $OUTPUT->render($select);
1672 if (!empty($activities)) {
1673 $select = new url_select($activities, '', array(''=>$straddactivity), "section$section");
1674 $select->set_help_icon('activities');
1675 $output .= $OUTPUT->render($select);
1678 if (!$vertical) {
1679 $output .= '</div>';
1682 $output .= '</div>';
1684 if ($return) {
1685 return $output;
1686 } else {
1687 echo $output;
1692 * Return the course category context for the category with id $categoryid, except
1693 * that if $categoryid is 0, return the system context.
1695 * @param integer $categoryid a category id or 0.
1696 * @return object the corresponding context
1698 function get_category_or_system_context($categoryid) {
1699 if ($categoryid) {
1700 return get_context_instance(CONTEXT_COURSECAT, $categoryid);
1701 } else {
1702 return get_context_instance(CONTEXT_SYSTEM);
1707 * Rebuilds the cached list of course activities stored in the database
1708 * @param int $courseid - id of course to rebuil, empty means all
1709 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1711 function rebuild_course_cache($courseid=0, $clearonly=false) {
1712 global $COURSE, $DB, $OUTPUT;
1714 if ($clearonly) {
1715 if (empty($courseid)) {
1716 $courseselect = array();
1717 } else {
1718 $courseselect = array('id'=>$courseid);
1720 $DB->set_field('course', 'modinfo', null, $courseselect);
1721 // update cached global COURSE too ;-)
1722 if ($courseid == $COURSE->id or empty($courseid)) {
1723 $COURSE->modinfo = null;
1725 // reset the fast modinfo cache
1726 $reset = 'reset';
1727 get_fast_modinfo($reset);
1728 return;
1731 if ($courseid) {
1732 $select = array('id'=>$courseid);
1733 } else {
1734 $select = array();
1735 @set_time_limit(0); // this could take a while! MDL-10954
1738 if ($rs = $DB->get_recordset("course", $select,'','id,fullname')) {
1739 foreach ($rs as $course) {
1740 $modinfo = serialize(get_array_of_activities($course->id));
1741 if (!$DB->set_field("course", "modinfo", $modinfo, array("id"=>$course->id))) {
1742 echo $OUTPUT->notification("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1744 // update cached global COURSE too ;-)
1745 if ($course->id == $COURSE->id) {
1746 $COURSE->modinfo = $modinfo;
1749 $rs->close();
1751 // reset the fast modinfo cache
1752 $reset = 'reset';
1753 get_fast_modinfo($reset);
1757 * Gets the child categories of a given coures category. Uses a static cache
1758 * to make repeat calls efficient.
1760 * @param unknown_type $parentid the id of a course category.
1761 * @return array all the child course categories.
1763 function get_child_categories($parentid) {
1764 static $allcategories = null;
1766 // only fill in this variable the first time
1767 if (null == $allcategories) {
1768 $allcategories = array();
1770 $categories = get_categories();
1771 foreach ($categories as $category) {
1772 if (empty($allcategories[$category->parent])) {
1773 $allcategories[$category->parent] = array();
1775 $allcategories[$category->parent][] = $category;
1779 if (empty($allcategories[$parentid])) {
1780 return array();
1781 } else {
1782 return $allcategories[$parentid];
1787 * This function recursively travels the categories, building up a nice list
1788 * for display. It also makes an array that list all the parents for each
1789 * category.
1791 * For example, if you have a tree of categories like:
1792 * Miscellaneous (id = 1)
1793 * Subcategory (id = 2)
1794 * Sub-subcategory (id = 4)
1795 * Other category (id = 3)
1796 * Then after calling this function you will have
1797 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1798 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1799 * 3 => 'Other category');
1800 * $parents = array(2 => array(1), 4 => array(1, 2));
1802 * If you specify $requiredcapability, then only categories where the current
1803 * user has that capability will be added to $list, although all categories
1804 * will still be added to $parents, and if you only have $requiredcapability
1805 * in a child category, not the parent, then the child catgegory will still be
1806 * included.
1808 * If you specify the option $excluded, then that category, and all its children,
1809 * are omitted from the tree. This is useful when you are doing something like
1810 * moving categories, where you do not want to allow people to move a category
1811 * to be the child of itself.
1813 * @param array $list For output, accumulates an array categoryid => full category path name
1814 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1815 * @param string/array $requiredcapability if given, only categories where the current
1816 * user has this capability will be added to $list. Can also be an array of capabilities,
1817 * in which case they are all required.
1818 * @param integer $excludeid Omit this category and its children from the lists built.
1819 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1820 * @param string $path For internal use, as part of recursive calls.
1822 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1823 $excludeid = 0, $category = NULL, $path = "") {
1825 // initialize the arrays if needed
1826 if (!is_array($list)) {
1827 $list = array();
1829 if (!is_array($parents)) {
1830 $parents = array();
1833 if (empty($category)) {
1834 // Start at the top level.
1835 $category = new stdClass;
1836 $category->id = 0;
1837 } else {
1838 // This is the excluded category, don't include it.
1839 if ($excludeid > 0 && $excludeid == $category->id) {
1840 return;
1843 // Update $path.
1844 if ($path) {
1845 $path = $path.' / '.format_string($category->name);
1846 } else {
1847 $path = format_string($category->name);
1850 // Add this category to $list, if the permissions check out.
1851 if (empty($requiredcapability)) {
1852 $list[$category->id] = $path;
1854 } else {
1855 ensure_context_subobj_present($category, CONTEXT_COURSECAT);
1856 $requiredcapability = (array)$requiredcapability;
1857 if (has_all_capabilities($requiredcapability, $category->context)) {
1858 $list[$category->id] = $path;
1863 // Add all the children recursively, while updating the parents array.
1864 if ($categories = get_child_categories($category->id)) {
1865 foreach ($categories as $cat) {
1866 if (!empty($category->id)) {
1867 if (isset($parents[$category->id])) {
1868 $parents[$cat->id] = $parents[$category->id];
1870 $parents[$cat->id][] = $category->id;
1872 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
1878 * This function generates a structured array of courses and categories.
1880 * The depth of categories is limited by $CFG->maxcategorydepth however there
1881 * is no limit on the number of courses!
1883 * Suitable for use with the course renderers course_category_tree method:
1884 * $renderer = $PAGE->get_renderer('core','course');
1885 * echo $renderer->course_category_tree(get_course_category_tree());
1887 * @global moodle_database $DB
1888 * @param int $id
1889 * @param int $depth
1891 function get_course_category_tree($id = 0, $depth = 0) {
1892 global $DB;
1893 $viewhiddencats = has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM));
1894 $categories = get_child_categories($id);
1895 $categoryids = array();
1896 foreach ($categories as $key => &$category) {
1897 if (!$category->visible && !$viewhiddencats) {
1898 unset($categories[$key]);
1899 continue;
1901 $categoryids[$category->id] = $category;
1902 if (empty($CFG->maxcategorydepth) || $depth <= $CFG->maxcategorydepth) {
1903 list($category->categories, $subcategories) = get_course_category_tree($category->id, $depth+1);
1904 foreach ($subcategories as $subid=>$subcat) {
1905 $categoryids[$subid] = $subcat;
1907 $category->courses = array();
1911 if ($depth > 0) {
1912 // This is a recursive call so return the required array
1913 return array($categories, $categoryids);
1916 // The depth is 0 this function has just been called so we can finish it off
1918 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1919 list($catsql, $catparams) = $DB->get_in_or_equal(array_keys($categoryids));
1920 $sql = "SELECT
1921 c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary,c.category
1922 $ccselect
1923 FROM {course} c
1924 $ccjoin
1925 WHERE c.category $catsql ORDER BY c.sortorder ASC";
1926 if ($courses = $DB->get_records_sql($sql, $catparams)) {
1927 // loop throught them
1928 foreach ($courses as $course) {
1929 if ($course->id == SITEID) {
1930 continue;
1932 context_instance_preload($course);
1933 if (!empty($course->visible) || has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
1934 $categoryids[$course->category]->courses[$course->id] = $course;
1938 return $categories;
1942 * Recursive function to print out all the categories in a nice format
1943 * with or without courses included
1945 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
1946 global $CFG;
1948 // maxcategorydepth == 0 meant no limit
1949 if (!empty($CFG->maxcategorydepth) && $depth >= $CFG->maxcategorydepth) {
1950 return;
1953 if (!$displaylist) {
1954 make_categories_list($displaylist, $parentslist);
1957 if ($category) {
1958 if ($category->visible or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM))) {
1959 print_category_info($category, $depth, $showcourses);
1960 } else {
1961 return; // Don't bother printing children of invisible categories
1964 } else {
1965 $category->id = "0";
1968 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
1969 $countcats = count($categories);
1970 $count = 0;
1971 $first = true;
1972 $last = false;
1973 foreach ($categories as $cat) {
1974 $count++;
1975 if ($count == $countcats) {
1976 $last = true;
1978 $up = $first ? false : true;
1979 $down = $last ? false : true;
1980 $first = false;
1982 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $showcourses);
1988 * This function will return $options array for html_writer::select(), with whitespace to denote nesting.
1990 function make_categories_options() {
1991 make_categories_list($cats,$parents);
1992 foreach ($cats as $key => $value) {
1993 if (array_key_exists($key,$parents)) {
1994 if ($indent = count($parents[$key])) {
1995 for ($i = 0; $i < $indent; $i++) {
1996 $cats[$key] = '&nbsp;'.$cats[$key];
2001 return $cats;
2005 * Prints the category info in indented fashion
2006 * This function is only used by print_whole_category_list() above
2008 function print_category_info($category, $depth, $showcourses = false) {
2009 global $CFG, $DB, $OUTPUT;
2011 $strsummary = get_string('summary');
2013 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
2015 static $coursecount = null;
2016 if (null === $coursecount) {
2017 // only need to check this once
2018 $coursecount = $DB->count_records('course') <= FRONTPAGECOURSELIMIT;
2021 if ($showcourses and $coursecount) {
2022 $catimage = '<img src="'.$OUTPUT->pix_url('i/course') . '" alt="" />';
2023 } else {
2024 $catimage = "&nbsp;";
2027 echo "\n\n".'<table class="categorylist">';
2029 $courses = get_courses($category->id, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.summary');
2030 if ($showcourses and $coursecount) {
2032 echo '<tr>';
2034 if ($depth) {
2035 $indent = $depth*30;
2036 $rows = count($courses) + 1;
2037 echo '<td class="category indentation" rowspan="'.$rows.'" valign="top">';
2039 echo $OUTPUT->spacer(array('height'=>10, 'width'=>$indent, 'br'=>true)); // should be done with CSS instead
2040 echo '</td>';
2043 echo '<td valign="top" class="category image">'.$catimage.'</td>';
2044 echo '<td valign="top" class="category name">';
2045 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
2046 echo '</td>';
2047 echo '<td class="category info">&nbsp;</td>';
2048 echo '</tr>';
2050 // does the depth exceed maxcategorydepth
2051 // maxcategorydepth == 0 or unset meant no limit
2053 $limit = !(isset($CFG->maxcategorydepth) && ($depth >= $CFG->maxcategorydepth-1));
2055 if ($courses && ($limit || $CFG->maxcategorydepth == 0)) {
2056 foreach ($courses as $course) {
2057 $linkcss = $course->visible ? '' : ' class="dimmed" ';
2058 echo '<tr><td valign="top">&nbsp;';
2059 echo '</td><td valign="top" class="course name">';
2060 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
2061 echo '</td><td align="right" valign="top" class="course info">';
2062 //TODO: add some guest, pay icons
2063 if ($course->summary) {
2064 $link = new moodle_url('/course/info.php?id='.$course->id);
2065 echo $OUTPUT->action_link($link, '<img alt="'.$strsummary.'" src="'.$OUTPUT->pix_url('i/info') . '" />',
2066 new popup_action('click', $link, 'courseinfo', array('height' => 400, 'width' => 500)),
2067 array('title'=>$strsummary));
2068 } else {
2069 echo '<img alt="" style="width:18px;height:16px;" src="'.$OUTPUT->pix_url('spacer') . '" />';
2071 echo '</td></tr>';
2074 } else {
2076 echo '<tr>';
2078 if ($depth) {
2079 $indent = $depth*20;
2080 echo '<td class="category indentation" valign="top">';
2081 echo $OUTPUT->spacer(array('height'=>10, 'width'=>$indent, 'br'=>true)); // should be done with CSS instead
2082 echo '</td>';
2085 echo '<td valign="top" class="category name">';
2086 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
2087 echo '</td>';
2088 echo '<td valign="top" class="category number">';
2089 if (count($courses)) {
2090 echo count($courses);
2092 echo '</td></tr>';
2094 echo '</table>';
2098 * Print the buttons relating to course requests.
2100 * @param object $systemcontext the system context.
2102 function print_course_request_buttons($systemcontext) {
2103 global $CFG, $DB, $OUTPUT;
2104 if (empty($CFG->enablecourserequests)) {
2105 return;
2107 if (!has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
2108 /// Print a button to request a new course
2109 echo $OUTPUT->single_button('request.php', get_string('requestcourse'), 'get');
2111 /// Print a button to manage pending requests
2112 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
2113 $disabled = !$DB->record_exists('course_request', array());
2114 echo $OUTPUT->single_button('pending.php', get_string('coursespending'), 'get', array('disabled'=>$disabled));
2119 * Does the user have permission to edit things in this category?
2121 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2122 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
2124 function can_edit_in_category($categoryid = 0) {
2125 $context = get_category_or_system_context($categoryid);
2126 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
2130 * Prints the turn editing on/off button on course/index.php or course/category.php.
2132 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
2133 * @return string HTML of the editing button, or empty string, if this user is not allowed
2134 * to see it.
2136 function update_category_button($categoryid = 0) {
2137 global $CFG, $PAGE, $OUTPUT;
2139 // Check permissions.
2140 if (!can_edit_in_category($categoryid)) {
2141 return '';
2144 // Work out the appropriate action.
2145 if ($PAGE->user_is_editing()) {
2146 $label = get_string('turneditingoff');
2147 $edit = 'off';
2148 } else {
2149 $label = get_string('turneditingon');
2150 $edit = 'on';
2153 // Generate the button HTML.
2154 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
2155 if ($categoryid) {
2156 $options['id'] = $categoryid;
2157 $page = 'category.php';
2158 } else {
2159 $page = 'index.php';
2161 return $OUTPUT->single_button(new moodle_url('/course/' . $page, $options), $label, 'get');
2165 * Category is 0 (for all courses) or an object
2167 function print_courses($category) {
2168 global $CFG, $OUTPUT;
2170 if (!is_object($category) && $category==0) {
2171 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
2172 if (is_array($categories) && count($categories) == 1) {
2173 $category = array_shift($categories);
2174 $courses = get_courses_wmanagers($category->id,
2175 'c.sortorder ASC',
2176 array('summary','summaryformat'));
2177 } else {
2178 $courses = get_courses_wmanagers('all',
2179 'c.sortorder ASC',
2180 array('summary','summaryformat'));
2182 unset($categories);
2183 } else {
2184 $courses = get_courses_wmanagers($category->id,
2185 'c.sortorder ASC',
2186 array('summary','summaryformat'));
2189 if ($courses) {
2190 echo '<ul class="unlist">';
2191 foreach ($courses as $course) {
2192 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
2193 if ($course->visible == 1 || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2194 echo '<li>';
2195 print_course($course);
2196 echo "</li>\n";
2199 echo "</ul>\n";
2200 } else {
2201 echo $OUTPUT->heading(get_string("nocoursesyet"));
2202 $context = get_context_instance(CONTEXT_SYSTEM);
2203 if (has_capability('moodle/course:create', $context)) {
2204 $options = array();
2205 if (!empty($category->id)) {
2206 $options['category'] = $category->id;
2207 } else {
2208 $options['category'] = $CFG->defaultrequestcategory;
2210 echo '<div class="addcoursebutton">';
2211 echo $OUTPUT->single_button(new moodle_url('/course/edit.php', $options), get_string("addnewcourse"));
2212 echo '</div>';
2218 * Print a description of a course, suitable for browsing in a list.
2220 * @param object $course the course object.
2221 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2223 function print_course($course, $highlightterms = '') {
2224 global $CFG, $USER, $DB, $OUTPUT;
2226 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2228 // Rewrite file URLs so that they are correct
2229 $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', NULL);
2231 $linkcss = $course->visible ? '' : ' class="dimmed" ';
2233 echo '<div class="coursebox clearfix">';
2234 echo '<div class="info">';
2235 echo '<h3 class="name"><a title="'.get_string('entercourse').'"'.
2236 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
2237 highlight($highlightterms, format_string($course->fullname)).'</a></h3>';
2239 /// first find all roles that are supposed to be displayed
2241 if (!empty($CFG->coursecontact)) {
2242 $managerroles = split(',', $CFG->coursecontact);
2243 $namesarray = array();
2244 if (isset($course->managers)) {
2245 if (count($course->managers)) {
2246 $rusers = $course->managers;
2247 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2249 /// Rename some of the role names if needed
2250 if (isset($context)) {
2251 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2254 // keep a note of users displayed to eliminate duplicates
2255 $usersshown = array();
2256 foreach ($rusers as $ra) {
2258 // if we've already displayed user don't again
2259 if (in_array($ra->user->id,$usersshown)) {
2260 continue;
2262 $usersshown[] = $ra->user->id;
2264 $fullname = fullname($ra->user, $canviewfullnames);
2266 if (isset($aliasnames[$ra->roleid])) {
2267 $ra->rolename = $aliasnames[$ra->roleid]->name;
2270 $namesarray[] = format_string($ra->rolename)
2271 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
2272 . $fullname . '</a>';
2275 } else {
2276 $rusers = get_role_users($managerroles, $context,
2277 true, '', 'r.sortorder ASC, u.lastname ASC');
2278 if (is_array($rusers) && count($rusers)) {
2279 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2281 /// Rename some of the role names if needed
2282 if (isset($context)) {
2283 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id), '', 'roleid,contextid,name');
2286 foreach ($rusers as $teacher) {
2287 $fullname = fullname($teacher, $canviewfullnames);
2289 /// Apply role names
2290 if (isset($aliasnames[$teacher->roleid])) {
2291 $teacher->rolename = $aliasnames[$teacher->roleid]->name;
2294 $namesarray[] = format_string($teacher->rolename)
2295 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
2296 . $fullname . '</a>';
2301 if (!empty($namesarray)) {
2302 echo "<ul class=\"teachers\">\n<li>";
2303 echo implode('</li><li>', $namesarray);
2304 echo "</li></ul>";
2308 // TODO: print some enrol icons
2310 echo '</div><div class="summary">';
2311 $options = NULL;
2312 $options->noclean = true;
2313 $options->para = false;
2314 if (!isset($course->summaryformat)) {
2315 $course->summaryformat = FORMAT_MOODLE;
2317 echo highlight($highlightterms, format_text($course->summary, $course->summaryformat, $options, $course->id));
2318 echo '</div>';
2319 echo '</div>';
2323 * Prints custom user information on the home page.
2324 * Over time this can include all sorts of information
2326 function print_my_moodle() {
2327 global $USER, $CFG, $DB, $OUTPUT;
2329 if (!isloggedin() or isguestuser()) {
2330 print_error('nopermissions', '', '', 'See My Moodle');
2333 $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC');
2334 $rhosts = array();
2335 $rcourses = array();
2336 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2337 $rcourses = get_my_remotecourses($USER->id);
2338 $rhosts = get_my_remotehosts();
2341 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2343 if (!empty($courses)) {
2344 echo '<ul class="unlist">';
2345 foreach ($courses as $course) {
2346 if ($course->id == SITEID) {
2347 continue;
2349 echo '<li>';
2350 print_course($course);
2351 echo "</li>\n";
2353 echo "</ul>\n";
2356 // MNET
2357 if (!empty($rcourses)) {
2358 // at the IDP, we know of all the remote courses
2359 foreach ($rcourses as $course) {
2360 print_remote_course($course, "100%");
2362 } elseif (!empty($rhosts)) {
2363 // non-IDP, we know of all the remote servers, but not courses
2364 foreach ($rhosts as $host) {
2365 print_remote_host($host, "100%");
2368 unset($course);
2369 unset($host);
2371 if ($DB->count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2372 echo "<table width=\"100%\"><tr><td align=\"center\">";
2373 print_course_search("", false, "short");
2374 echo "</td><td align=\"center\">";
2375 echo $OUTPUT->single_button("$CFG->wwwroot/course/index.php", get_string("fulllistofcourses"), "get");
2376 echo "</td></tr></table>\n";
2379 } else {
2380 if ($DB->count_records("course_categories") > 1) {
2381 echo $OUTPUT->box_start("categorybox");
2382 print_whole_category_list();
2383 echo $OUTPUT->box_end();
2384 } else {
2385 print_courses(0);
2391 function print_course_search($value="", $return=false, $format="plain") {
2392 global $CFG;
2393 static $count = 0;
2395 $count++;
2397 $id = 'coursesearch';
2399 if ($count > 1) {
2400 $id .= $count;
2403 $strsearchcourses= get_string("searchcourses");
2405 if ($format == 'plain') {
2406 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2407 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2408 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2409 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value).'" />';
2410 $output .= '<input type="submit" value="'.get_string('go').'" />';
2411 $output .= '</fieldset></form>';
2412 } else if ($format == 'short') {
2413 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2414 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2415 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2416 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2417 $output .= '<input type="submit" value="'.get_string('go').'" />';
2418 $output .= '</fieldset></form>';
2419 } else if ($format == 'navbar') {
2420 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2421 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2422 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2423 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value).'" />';
2424 $output .= '<input type="submit" value="'.get_string('go').'" />';
2425 $output .= '</fieldset></form>';
2428 if ($return) {
2429 return $output;
2431 echo $output;
2434 function print_remote_course($course, $width="100%") {
2435 global $CFG, $USER;
2437 $linkcss = '';
2439 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2441 echo '<div class="coursebox remotecoursebox clearfix">';
2442 echo '<div class="info">';
2443 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2444 $linkcss.' href="'.$url.'">'
2445 . format_string($course->fullname) .'</a><br />'
2446 . format_string($course->hostname) . ' : '
2447 . format_string($course->cat_name) . ' : '
2448 . format_string($course->shortname). '</div>';
2449 echo '</div><div class="summary">';
2450 $options = NULL;
2451 $options->noclean = true;
2452 $options->para = false;
2453 echo format_text($course->summary, FORMAT_MOODLE, $options);
2454 echo '</div>';
2455 echo '</div>';
2458 function print_remote_host($host, $width="100%") {
2459 global $OUTPUT;
2461 $linkcss = '';
2463 echo '<div class="coursebox clearfix">';
2464 echo '<div class="info">';
2465 echo '<div class="name">';
2466 echo '<img src="'.$OUTPUT->pix_url('i/mnethost') . '" class="icon" alt="'.get_string('course').'" />';
2467 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2468 . s($host['name']).'</a> - ';
2469 echo $host['count'] . ' ' . get_string('courses');
2470 echo '</div>';
2471 echo '</div>';
2472 echo '</div>';
2476 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2478 function add_course_module($mod) {
2479 global $DB;
2481 $mod->added = time();
2482 unset($mod->id);
2484 return $DB->insert_record("course_modules", $mod);
2488 * Returns course section - creates new if does not exist yet.
2489 * @param int $relative section number
2490 * @param int $courseid
2491 * @return object $course_section object
2493 function get_course_section($section, $courseid) {
2494 global $DB;
2496 if ($cw = $DB->get_record("course_sections", array("section"=>$section, "course"=>$courseid))) {
2497 return $cw;
2499 $cw = new object();
2500 $cw->course = $courseid;
2501 $cw->section = $section;
2502 $cw->summary = "";
2503 $cw->summaryformat = FORMAT_HTML;
2504 $cw->sequence = "";
2505 $id = $DB->insert_record("course_sections", $cw);
2506 return $DB->get_record("course_sections", array("id"=>$id));
2509 * Given a full mod object with section and course already defined, adds this module to that section.
2511 * @param object $mod
2512 * @param int $beforemod An existing ID which we will insert the new module before
2513 * @return int The course_sections ID where the mod is inserted
2515 function add_mod_to_section($mod, $beforemod=NULL) {
2516 global $DB;
2518 if ($section = $DB->get_record("course_sections", array("course"=>$mod->course, "section"=>$mod->section))) {
2520 $section->sequence = trim($section->sequence);
2522 if (empty($section->sequence)) {
2523 $newsequence = "$mod->coursemodule";
2525 } else if ($beforemod) {
2526 $modarray = explode(",", $section->sequence);
2528 if ($key = array_keys($modarray, $beforemod->id)) {
2529 $insertarray = array($mod->id, $beforemod->id);
2530 array_splice($modarray, $key[0], 1, $insertarray);
2531 $newsequence = implode(",", $modarray);
2533 } else { // Just tack it on the end anyway
2534 $newsequence = "$section->sequence,$mod->coursemodule";
2537 } else {
2538 $newsequence = "$section->sequence,$mod->coursemodule";
2541 if ($DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id))) {
2542 return $section->id; // Return course_sections ID that was used.
2543 } else {
2544 return 0;
2547 } else { // Insert a new record
2548 $section->course = $mod->course;
2549 $section->section = $mod->section;
2550 $section->summary = "";
2551 $section->summaryformat = FORMAT_HTML;
2552 $section->sequence = $mod->coursemodule;
2553 return $DB->insert_record("course_sections", $section);
2557 function set_coursemodule_groupmode($id, $groupmode) {
2558 global $DB;
2559 return $DB->set_field("course_modules", "groupmode", $groupmode, array("id"=>$id));
2562 function set_coursemodule_idnumber($id, $idnumber) {
2563 global $DB;
2564 return $DB->set_field("course_modules", "idnumber", $idnumber, array("id"=>$id));
2568 * $prevstateoverrides = true will set the visibility of the course module
2569 * to what is defined in visibleold. This enables us to remember the current
2570 * visibility when making a whole section hidden, so that when we toggle
2571 * that section back to visible, we are able to return the visibility of
2572 * the course module back to what it was originally.
2574 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2575 global $DB;
2576 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2577 return false;
2579 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
2580 return false;
2582 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2583 foreach($events as $event) {
2584 if ($visible) {
2585 show_event($event);
2586 } else {
2587 hide_event($event);
2591 if ($prevstateoverrides) {
2592 if ($visible == '0') {
2593 // Remember the current visible state so we can toggle this back.
2594 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id'=>$id));
2595 } else {
2596 // Get the previous saved visible states.
2597 return $DB->set_field('course_modules', 'visible', $cm->visibleold, array('id'=>$id));
2600 return $DB->set_field("course_modules", "visible", $visible, array("id"=>$id));
2604 * Delete a course module and any associated data at the course level (events)
2605 * Until 1.5 this function simply marked a deleted flag ... now it
2606 * deletes it completely.
2609 function delete_course_module($id) {
2610 global $CFG, $DB;
2611 require_once($CFG->libdir.'/gradelib.php');
2612 require_once($CFG->dirroot.'/blog/lib.php');
2614 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
2615 return true;
2617 $modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module));
2618 //delete events from calendar
2619 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
2620 foreach($events as $event) {
2621 delete_event($event->id);
2624 //delete grade items, outcome items and grades attached to modules
2625 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2626 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2627 foreach ($grade_items as $grade_item) {
2628 $grade_item->delete('moddelete');
2632 delete_context(CONTEXT_MODULE, $cm->id);
2633 return $DB->delete_records('course_modules', array('id'=>$cm->id));
2636 function delete_mod_from_section($mod, $section) {
2637 global $DB;
2639 if ($section = $DB->get_record("course_sections", array("id"=>$section)) ) {
2641 $modarray = explode(",", $section->sequence);
2643 if ($key = array_keys ($modarray, $mod)) {
2644 array_splice($modarray, $key[0], 1);
2645 $newsequence = implode(",", $modarray);
2646 return $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
2647 } else {
2648 return false;
2652 return false;
2656 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2658 * @param object $course
2659 * @param int $section
2660 * @param int $move (-1 or 1)
2662 function move_section($course, $section, $move) {
2663 /// Moves a whole course section up and down within the course
2664 global $USER, $DB;
2666 if (!$move) {
2667 return true;
2670 $sectiondest = $section + $move;
2672 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2673 return false;
2676 if (!$sectionrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$section))) {
2677 return false;
2680 if (!$sectiondestrecord = $DB->get_record("course_sections", array("course"=>$course->id, "section"=>$sectiondest))) {
2681 return false;
2684 if (!$DB->set_field("course_sections", "section", $sectiondest, array("id"=>$sectionrecord->id))) {
2685 return false;
2687 if (!$DB->set_field("course_sections", "section", $section, array("id"=>$sectiondestrecord->id))) {
2688 return false;
2690 // if the focus is on the section that is being moved, then move the focus along
2691 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2692 course_set_display($course->id, $sectiondest);
2695 // Check for duplicates and fix order if needed.
2696 // There is a very rare case that some sections in the same course have the same section id.
2697 $sections = $DB->get_records('course_sections', array('course'=>$course->id), 'section ASC');
2698 $n = 0;
2699 foreach ($sections as $section) {
2700 if ($section->section != $n) {
2701 if (!$DB->set_field('course_sections', 'section', $n, array('id'=>$section->id))) {
2702 return false;
2705 $n++;
2707 return true;
2711 * Moves a section within a course, from a position to another.
2712 * Be very careful: $section and $destination refer to section number,
2713 * not id!.
2715 * @param object $course
2716 * @param int $section Section number (not id!!!)
2717 * @param int $destination
2718 * @return boolean Result
2720 function move_section_to($course, $section, $destination) {
2721 /// Moves a whole course section up and down within the course
2722 global $USER, $DB;
2724 if (!$destination && $destination != 0) {
2725 return true;
2728 if ($destination > $course->numsections) {
2729 return false;
2732 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2733 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
2734 'section ASC, id ASC', 'id, section')) {
2735 return false;
2738 $sections = reorder_sections($sections, $section, $destination);
2740 // Update all sections
2741 foreach ($sections as $id => $position) {
2742 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
2745 // if the focus is on the section that is being moved, then move the focus along
2746 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2747 course_set_display($course->id, $destination);
2749 return true;
2753 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2754 * an original position number and a target position number, rebuilds the array so that the
2755 * move is made without any duplication of section positions.
2756 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2757 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2759 * @param array $sections
2760 * @param int $origin_position
2761 * @param int $target_position
2762 * @return array
2764 function reorder_sections($sections, $origin_position, $target_position) {
2765 if (!is_array($sections)) {
2766 return false;
2769 // We can't move section position 0
2770 if ($origin_position < 1) {
2771 echo "We can't move section position 0";
2772 return false;
2775 // Locate origin section in sections array
2776 if (!$origin_key = array_search($origin_position, $sections)) {
2777 echo "searched position not in sections array";
2778 return false; // searched position not in sections array
2781 // Extract origin section
2782 $origin_section = $sections[$origin_key];
2783 unset($sections[$origin_key]);
2785 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2786 $found = false;
2787 $append_array = array();
2788 foreach ($sections as $id => $position) {
2789 if ($found) {
2790 $append_array[$id] = $position;
2791 unset($sections[$id]);
2793 if ($position == $target_position) {
2794 $found = true;
2798 // Append moved section
2799 $sections[$origin_key] = $origin_section;
2801 // Append rest of array (if applicable)
2802 if (!empty($append_array)) {
2803 foreach ($append_array as $id => $position) {
2804 $sections[$id] = $position;
2808 // Renumber positions
2809 $position = 0;
2810 foreach ($sections as $id => $p) {
2811 $sections[$id] = $position;
2812 $position++;
2815 return $sections;
2820 * Move the module object $mod to the specified $section
2821 * If $beforemod exists then that is the module
2822 * before which $modid should be inserted
2823 * All parameters are objects
2825 function moveto_module($mod, $section, $beforemod=NULL) {
2826 global $DB, $OUTPUT;
2828 /// Remove original module from original section
2829 if (! delete_mod_from_section($mod->id, $mod->section)) {
2830 echo $OUTPUT->notification("Could not delete module from existing section");
2833 /// Update module itself if necessary
2835 if ($mod->section != $section->id) {
2836 $mod->section = $section->id;
2837 $DB->update_record("course_modules", $mod);
2838 // if moving to a hidden section then hide module
2839 if (!$section->visible) {
2840 set_coursemodule_visible($mod->id, 0);
2844 /// Add the module into the new section
2846 $mod->course = $section->course;
2847 $mod->section = $section->section; // need relative reference
2848 $mod->coursemodule = $mod->id;
2850 if (! add_mod_to_section($mod, $beforemod)) {
2851 return false;
2854 return true;
2857 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2858 global $CFG, $USER, $DB, $OUTPUT;
2860 static $str;
2861 static $sesskey;
2863 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2864 // no permission to edit
2865 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2866 return false;
2869 if (!isset($str)) {
2870 $str->assign = get_string("assignroles", 'role');
2871 $str->delete = get_string("delete");
2872 $str->move = get_string("move");
2873 $str->moveup = get_string("moveup");
2874 $str->movedown = get_string("movedown");
2875 $str->moveright = get_string("moveright");
2876 $str->moveleft = get_string("moveleft");
2877 $str->update = get_string("update");
2878 $str->duplicate = get_string("duplicate");
2879 $str->hide = get_string("hide");
2880 $str->show = get_string("show");
2881 $str->clicktochange = get_string("clicktochange");
2882 $str->forcedmode = get_string("forcedmode");
2883 $str->groupsnone = get_string("groupsnone");
2884 $str->groupsseparate = get_string("groupsseparate");
2885 $str->groupsvisible = get_string("groupsvisible");
2886 $sesskey = sesskey();
2889 if ($section >= 0) {
2890 $section = '&amp;sr='.$section; // Section return
2891 } else {
2892 $section = '';
2895 if ($absolute) {
2896 $path = $CFG->wwwroot.'/course';
2897 } else {
2898 $path = '.';
2900 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2901 if ($mod->visible) {
2902 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2903 '&amp;sesskey='.$sesskey.$section.'"><img'.
2904 ' src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" '.
2905 ' alt="'.$str->hide.'" /></a>'."\n";
2906 } else {
2907 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2908 '&amp;sesskey='.$sesskey.$section.'"><img'.
2909 ' src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" '.
2910 ' alt="'.$str->show.'" /></a>'."\n";
2912 } else {
2913 $hideshow = '';
2916 if ($mod->groupmode !== false) {
2917 if ($mod->groupmode == SEPARATEGROUPS) {
2918 $grouptitle = $str->groupsseparate;
2919 $groupclass = 'editing_groupsseparate';
2920 $groupimage = $OUTPUT->pix_url('t/groups') . '';
2921 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2922 } else if ($mod->groupmode == VISIBLEGROUPS) {
2923 $grouptitle = $str->groupsvisible;
2924 $groupclass = 'editing_groupsvisible';
2925 $groupimage = $OUTPUT->pix_url('t/groupv') . '';
2926 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2927 } else {
2928 $grouptitle = $str->groupsnone;
2929 $groupclass = 'editing_groupsnone';
2930 $groupimage = $OUTPUT->pix_url('t/groupn') . '';
2931 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2933 if ($mod->groupmodelink) {
2934 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2935 '<img src="'.$groupimage.'" class="iconsmall" '.
2936 'alt="'.$grouptitle.'" /></a>';
2937 } else {
2938 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2939 ' src="'.$groupimage.'" class="iconsmall" '.
2940 'alt="'.$grouptitle.'" />';
2942 } else {
2943 $groupmode = "";
2946 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2947 if ($moveselect) {
2948 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2949 '&amp;sesskey='.$sesskey.$section.'"><img'.
2950 ' src="'.$OUTPUT->pix_url('t/move') . '" class="iconsmall" '.
2951 ' alt="'.$str->move.'" /></a>'."\n";
2952 } else {
2953 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2954 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2955 ' src="'.$OUTPUT->pix_url('t/up') . '" class="iconsmall" '.
2956 ' alt="'.$str->moveup.'" /></a>'."\n".
2957 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2958 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2959 ' src="'.$OUTPUT->pix_url('t/down') . '" class="iconsmall" '.
2960 ' alt="'.$str->movedown.'" /></a>'."\n";
2962 } else {
2963 $move = '';
2966 $leftright = '';
2967 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2969 if (right_to_left()) { // Exchange arrows on RTL
2970 $rightarrow = 't/left';
2971 $leftarrow = 't/right';
2972 } else {
2973 $rightarrow = 't/right';
2974 $leftarrow = 't/left';
2977 if ($indent > 0) {
2978 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2979 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2980 ' src="'.$OUTPUT->pix_url($leftarrow).'" class="iconsmall" '.
2981 ' alt="'.$str->moveleft.'" /></a>'."\n";
2983 if ($indent >= 0) {
2984 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2985 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2986 ' src="'.$OUTPUT->pix_url($rightarrow).'" class="iconsmall" '.
2987 ' alt="'.$str->moveright.'" /></a>'."\n";
2990 if (has_capability('moodle/course:managegroups', $modcontext)){
2991 $context = get_context_instance(CONTEXT_MODULE, $mod->id);
2992 $assign = '<a class="editing_assign" title="'.$str->assign.'" href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.
2993 $context->id.'"><img src="'.$OUTPUT->pix_url('i/roles') . '" alt="'.$str->assign.'" class="iconsmall"/></a>';
2994 } else {
2995 $assign = '';
2998 return '<span class="commands">'."\n".$leftright.$move.
2999 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
3000 '&amp;sesskey='.$sesskey.$section.'"><img'.
3001 ' src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" '.
3002 ' alt="'.$str->update.'" /></a>'."\n".
3003 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
3004 '&amp;sesskey='.$sesskey.$section.'"><img'.
3005 ' src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" '.
3006 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".$assign.'</span>';
3010 * given a course object with shortname & fullname, this function will
3011 * truncate the the number of chars allowed and add ... if it was too long
3013 function course_format_name ($course,$max=100) {
3015 $str = $course->shortname.': '. $course->fullname;
3016 if (strlen($str) <= $max) {
3017 return $str;
3019 else {
3020 return substr($str,0,$max-3).'...';
3024 function update_restricted_mods($course, $mods) {
3025 global $DB;
3027 /// Delete all the current restricted list
3028 $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
3030 if (empty($course->restrictmodules)) {
3031 return; // We're done
3034 /// Insert the new list of restricted mods
3035 foreach ($mods as $mod) {
3036 if ($mod == 0) {
3037 continue; // this is the 'allow none' option
3039 $am = new object();
3040 $am->course = $course->id;
3041 $am->module = $mod;
3042 $DB->insert_record('course_allowed_modules',$am);
3047 * This function will take an int (module id) or a string (module name)
3048 * and return true or false, whether it's allowed in the given course (object)
3049 * $mod is not allowed to be an object, as the field for the module id is inconsistent
3050 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
3053 function course_allowed_module($course,$mod) {
3054 global $DB;
3056 if (empty($course->restrictmodules)) {
3057 return true;
3060 // Admins and admin-like people who can edit everything can also add anything.
3061 // Originally there was a coruse:update test only, but it did not match the test in course edit form
3062 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3063 return true;
3066 if (is_numeric($mod)) {
3067 $modid = $mod;
3068 } else if (is_string($mod)) {
3069 $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
3071 if (empty($modid)) {
3072 return false;
3075 return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
3079 * Recursively delete category including all subcategories and courses.
3080 * @param object $category
3081 * @param boolean $showfeedback display some notices
3082 * @return array return deleted courses
3084 function category_delete_full($category, $showfeedback=true) {
3085 global $CFG, $DB;
3086 require_once($CFG->libdir.'/gradelib.php');
3087 require_once($CFG->libdir.'/questionlib.php');
3088 require_once($CFG->dirroot.'/cohort/lib.php');
3090 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3091 foreach ($children as $childcat) {
3092 category_delete_full($childcat, $showfeedback);
3096 $deletedcourses = array();
3097 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC')) {
3098 foreach ($courses as $course) {
3099 if (!delete_course($course, false)) {
3100 throw new moodle_exception('cannotdeletecategorycourse','','',$course->shortname);
3102 $deletedcourses[] = $course;
3106 // move or delete cohorts in this context
3107 cohort_delete_category($category);
3109 // now delete anything that may depend on course category context
3110 grade_course_category_delete($category->id, 0, $showfeedback);
3111 if (!question_delete_course_category($category, 0, $showfeedback)) {
3112 throw new moodle_exception('cannotdeletecategoryquestions','','',$category->name);
3115 // finally delete the category and it's context
3116 $DB->delete_records('course_categories', array('id'=>$category->id));
3117 delete_context(CONTEXT_COURSECAT, $category->id);
3119 events_trigger('course_category_deleted', $category);
3121 return $deletedcourses;
3125 * Delete category, but move contents to another category.
3126 * @param object $ccategory
3127 * @param int $newparentid category id
3128 * @return bool status
3130 function category_delete_move($category, $newparentid, $showfeedback=true) {
3131 global $CFG, $DB, $OUTPUT;
3132 require_once($CFG->libdir.'/gradelib.php');
3133 require_once($CFG->libdir.'/questionlib.php');
3134 require_once($CFG->dirroot.'/cohort/lib.php');
3136 if (!$newparentcat = $DB->get_record('course_categories', array('id'=>$newparentid))) {
3137 return false;
3140 if ($children = $DB->get_records('course_categories', array('parent'=>$category->id), 'sortorder ASC')) {
3141 foreach ($children as $childcat) {
3142 move_category($childcat, $newparentcat);
3146 if ($courses = $DB->get_records('course', array('category'=>$category->id), 'sortorder ASC', 'id')) {
3147 if (!move_courses(array_keys($courses), $newparentid)) {
3148 echo $OUTPUT->notification("Error moving courses");
3149 return false;
3151 echo $OUTPUT->notification(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
3154 // move or delete cohorts in this context
3155 cohort_delete_category($category);
3157 // now delete anything that may depend on course category context
3158 grade_course_category_delete($category->id, $newparentid, $showfeedback);
3159 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3160 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3161 return false;
3164 // finally delete the category and it's context
3165 $DB->delete_records('course_categories', array('id'=>$category->id));
3166 delete_context(CONTEXT_COURSECAT, $category->id);
3168 events_trigger('course_category_deleted', $category);
3170 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
3172 return true;
3176 * Efficiently moves many courses around while maintaining
3177 * sortorder in order.
3179 * @param $courseids is an array of course ids
3180 * @return bool success
3182 function move_courses($courseids, $categoryid) {
3183 global $CFG, $DB, $OUTPUT;
3185 if (empty($courseids)) {
3186 // nothing to do
3187 return;
3190 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
3191 return false;
3194 $courseids = array_reverse($courseids);
3195 $i = 1;
3197 foreach ($courseids as $courseid) {
3198 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
3199 $course->category = $category->id;
3200 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
3201 if ($category->visible == 0) {
3202 // hide the course when moving into hidden category,
3203 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
3204 $course->visible = 0;
3207 $DB->update_record('course', $course);
3209 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3210 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3211 context_moved($context, $newparent);
3214 fix_course_sortorder();
3216 return true;
3220 * Hide course category and child course and subcategories
3221 * @param $category
3222 * @return void
3224 function course_category_hide($category) {
3225 global $DB;
3227 $category->visible = 0;
3228 $DB->set_field('course_categories', 'visible', 0, array('id'=>$category->id));
3229 $DB->set_field('course_categories', 'visibleold', 0, array('id'=>$category->id));
3230 $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
3231 $DB->set_field('course', 'visible', 0, array('category' => $category->id));
3232 // get all child categories and hide too
3233 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3234 foreach ($subcats as $cat) {
3235 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id'=>$cat->id));
3236 $DB->set_field('course_categories', 'visible', 0, array('id'=>$cat->id));
3237 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
3238 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
3244 * Show course category and child course and subcategories
3245 * @param $category
3246 * @return void
3248 function course_category_show($category) {
3249 global $DB;
3251 $category->visible = 1;
3252 $DB->set_field('course_categories', 'visible', 1, array('id'=>$category->id));
3253 $DB->set_field('course_categories', 'visibleold', 1, array('id'=>$category->id));
3254 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($category->id));
3255 // get all child categories and unhide too
3256 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$category->path/%"))) {
3257 foreach ($subcats as $cat) {
3258 if ($cat->visibleold) {
3259 $DB->set_field('course_categories', 'visible', 1, array('id'=>$cat->id));
3261 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
3267 * Efficiently moves a category - NOTE that this can have
3268 * a huge impact access-control-wise...
3270 function move_category($category, $newparentcat) {
3271 global $CFG, $DB;
3273 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
3275 $hidecat = false;
3276 if (empty($newparentcat->id)) {
3277 $DB->set_field('course_categories', 'parent', 0, array('id'=>$category->id));
3279 $newparent = get_context_instance(CONTEXT_SYSTEM);
3281 } else {
3282 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id'=>$category->id));
3283 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3285 if (!$newparentcat->visible and $category->visible) {
3286 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
3287 $hidecat = true;
3291 context_moved($context, $newparent);
3293 // now make it last in new category
3294 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id'=>$category->id));
3296 // and fix the sortorders
3297 fix_course_sortorder();
3299 if ($hidecat) {
3300 course_category_hide($category);
3305 * Returns the display name of the given section that the course prefers.
3307 * This function utilizes a callback that can be implemented within the course
3308 * formats lib.php file to customize the display name that is used to reference
3309 * the section.
3311 * By default (if callback is not defined) the method
3312 * {@see get_numeric_section_name} is called instead.
3314 * @param stdClass $course The course to get the section name for
3315 * @param stdClass $section Section object from database
3316 * @return Display name that the course format prefers, e.g. "Week 2"
3318 * @see get_generic_section_name
3320 function get_section_name(stdClass $course, stdClass $section) {
3321 global $CFG;
3323 /// Inelegant hack for bug 3408
3324 if ($course->format == 'site') {
3325 return get_string('site');
3328 // Use course formatter callback if it exists
3329 $namingfile = $CFG->dirroot.'/course/format/'.$course->format.'/lib.php';
3330 $namingfunction = 'callback_'.$course->format.'_get_section_name';
3331 if (!function_exists($namingfunction) && file_exists($namingfile)) {
3332 require_once $namingfile;
3334 if (function_exists($namingfunction)) {
3335 return $namingfunction($course, $section);
3338 // else, default behavior:
3339 return get_generic_section_name($course->format, $section);
3343 * Gets the generic section name for a courses section.
3345 * @param string $format Course format ID e.g. 'weeks' $course->format
3346 * @param stdClass $section Section object from database
3347 * @return Display name that the course format prefers, e.g. "Week 2"
3349 function get_generic_section_name($format, stdClass $section) {
3350 return get_string('sectionname', "format_$format") . ' ' . $section->section;
3354 function course_format_uses_sections($format) {
3355 global $CFG;
3357 $featurefile = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
3358 $featurefunction = 'callback_'.$format.'_uses_sections';
3359 if (!function_exists($featurefunction) && file_exists($featurefile)) {
3360 require_once $featurefile;
3362 if (function_exists($featurefunction)) {
3363 return $featurefunction();
3366 return false;
3370 * Can the current user delete this course?
3371 * Course creators have exception,
3372 * 1 day after the creation they can sill delete the course.
3373 * @param int $courseid
3374 * @return boolean
3376 function can_delete_course($courseid) {
3377 global $USER, $DB;
3379 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3381 if (has_capability('moodle/course:delete', $context)) {
3382 return true;
3385 // hack: now try to find out if creator created this course recently (1 day)
3386 if (!has_capability('moodle/course:create', $context)) {
3387 return false;
3390 $since = time() - 60*60*24;
3392 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
3393 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
3395 return $DB->record_exists_select('log', $select, $params);
3399 * Save the Your name for 'Some role' strings.
3401 * @param integer $courseid the id of this course.
3402 * @param array $data the data that came from the course settings form.
3404 function save_local_role_names($courseid, $data) {
3405 global $DB;
3406 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3408 foreach ($data as $fieldname => $value) {
3409 if (strpos($fieldname, 'role_') !== 0) {
3410 continue;
3412 list($ignored, $roleid) = explode('_', $fieldname);
3414 // make up our mind whether we want to delete, update or insert
3415 if (!$value) {
3416 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
3418 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
3419 $rolename->name = $value;
3420 $DB->update_record('role_names', $rolename);
3422 } else {
3423 $rolename = new stdClass;
3424 $rolename->contextid = $context->id;
3425 $rolename->roleid = $roleid;
3426 $rolename->name = $value;
3427 $DB->insert_record('role_names', $rolename);
3433 * Create a course and either return a $course object
3435 * Please note this functions does not verify any access control,
3436 * the calling code is responsible for all validation (usually it is the form definition).
3438 * @param array $editoroptions course description editor options
3439 * @param object $data - all the data needed for an entry in the 'course' table
3440 * @return object new course instance
3442 function create_course($data, $editoroptions = NULL) {
3443 global $CFG, $DB;
3445 //check the categoryid - must be given for all new courses
3446 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
3448 //check if the shortname already exist
3449 if (!empty($data->shortname)) {
3450 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
3451 throw new moodle_exception('shortnametaken');
3455 //check if the id number already exist
3456 if (!empty($data->idnumber)) {
3457 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
3458 throw new moodle_exception('idnumbertaken');
3462 $data->timecreated = time();
3463 $data->timemodified = $data->timecreated;
3465 // place at beginning of any category
3466 $data->sortorder = 0;
3468 if ($editoroptions) {
3469 // summary text is updated later, we need context to store the files first
3470 $data->summary = '';
3471 $data->summary_format = FORMAT_HTML;
3474 // init visible flags
3475 if (isset($data->visible)) {
3476 $data->visibleold = $data->visible;
3477 } else {
3478 $data->visibleold = $data->visible = 1;
3481 $newcourseid = $DB->insert_record('course', $data);
3482 $context = get_context_instance(CONTEXT_COURSE, $newcourseid, MUST_EXIST);
3484 if ($editoroptions) {
3485 // Save the files used in the summary editor and store
3486 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3487 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
3488 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
3491 $course = $DB->get_record('course', array('id'=>$newcourseid));
3493 // Setup the blocks
3494 blocks_add_default_course_blocks($course);
3496 $section = new object();
3497 $section->course = $course->id; // Create a default section.
3498 $section->section = 0;
3499 $section->summaryformat = FORMAT_HTML;
3500 $DB->insert_record('course_sections', $section);
3502 fix_course_sortorder();
3504 // update module restrictions
3505 if ($course->restrictmodules) {
3506 if (isset($data->allowedmods)) {
3507 update_restricted_mods($course, $allowedmods);
3508 } else {
3509 if (!empty($CFG->defaultallowedmodules)) {
3510 update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
3515 // new context created - better mark it as dirty
3516 mark_context_dirty($context->path);
3518 // Save any custom role names.
3519 save_local_role_names($course->id, $data);
3521 // set up enrolments
3522 enrol_course_updated(true, $course, $data);
3524 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3526 // Trigger events
3527 events_trigger('course_created', $course);
3529 return $course;
3533 * Update a course.
3535 * Please note this functions does not verify any access control,
3536 * the calling code is responsible for all validation (usually it is the form definition).
3538 * @param object $data - all the data needed for an entry in the 'course' table
3539 * @param array $editoroptions course description editor options
3540 * @return void
3542 function update_course($data, $editoroptions = NULL) {
3543 global $CFG, $DB;
3545 $data->timemodified = time();
3547 $oldcourse = $DB->get_record('course', array('id'=>$data->id), '*', MUST_EXIST);
3548 $context = get_context_instance(CONTEXT_COURSE, $oldcourse->id);
3550 if ($editoroptions) {
3551 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
3554 if (!isset($data->category) or empty($data->category)) {
3555 // prevent nulls and 0 in category field
3556 unset($data->category);
3558 $movecat = (isset($data->category) and $oldcourse->category != $data->category);
3560 // init visible flags
3561 if (isset($data->visible)) {
3562 $data->visible = $oldcourse->visible;
3565 if ($data->visible != $oldcourse->visible) {
3566 // reset the visibleold flag when manually hiding/unhiding course
3567 $data->visibleold = $data->visible;
3568 } else {
3569 if ($movecat) {
3570 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
3571 if (empty($newcategory->visible)) {
3572 // make sure when moving into hidden category the course is hidden automatically
3573 $data->visible = 0;
3578 // Update with the new data
3579 $DB->update_record('course', $data);
3581 $course = $DB->get_record('course', array('id'=>$data->id));
3583 if ($movecat) {
3584 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3585 context_moved($context, $newparent);
3588 fix_course_sortorder();
3590 // Test for and remove blocks which aren't appropriate anymore
3591 blocks_remove_inappropriate($course);
3593 // update module restrictions
3594 if (isset($data->allowedmods)) {
3595 update_restricted_mods($course, $allowedmods);
3598 // Save any custom role names.
3599 save_local_role_names($course->id, $data);
3601 // update enrol settings
3602 enrol_course_updated(false, $course, $data);
3604 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3606 // Trigger events
3607 events_trigger('course_updated', $course);
3611 * TODO: Average number of participants (in non-empty courses)
3612 * @return integer
3614 function average_number_of_participants() {
3615 global $DB;
3616 return 0;
3617 return $avg;
3621 * TODO: Average number of course modules (in non-empty courses)
3622 * @return integer
3624 function average_number_of_courses_modules() {
3625 global $DB;
3626 return 0;
3627 return $avg;
3631 * This class pertains to course requests and contains methods associated with
3632 * create, approving, and removing course requests.
3634 * Please note we do not allow embedded images here because there is no context
3635 * to store them with proper access control.
3637 * @copyright 2009 Sam Hemelryk
3638 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3639 * @since Moodle 2.0
3641 * @property-read int $id
3642 * @property-read string $fullname
3643 * @property-read string $shortname
3644 * @property-read string $summary
3645 * @property-read int $summaryformat
3646 * @property-read int $summarytrust
3647 * @property-read string $reason
3648 * @property-read int $requester
3650 class course_request {
3653 * This is the stdClass that stores the properties for the course request
3654 * and is externally acccessed through the __get magic method
3655 * @var stdClass
3657 protected $properties;
3660 * An array of options for the summary editor used by course request forms.
3661 * This is initially set by {@link summary_editor_options()}
3662 * @var array
3663 * @static
3665 protected static $summaryeditoroptions;
3668 * Static function to prepare the summary editor for working with a course
3669 * request.
3671 * @static
3672 * @param null|stdClass $data Optional, an object containing the default values
3673 * for the form, these may be modified when preparing the
3674 * editor so this should be called before creating the form
3675 * @return stdClass An object that can be used to set the default values for
3676 * an mforms form
3678 public static function prepare($data=null) {
3679 if ($data === null) {
3680 $data = new stdClass;
3682 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
3683 return $data;
3687 * Static function to create a new course request when passed an array of properties
3688 * for it.
3690 * This function also handles saving any files that may have been used in the editor
3692 * @static
3693 * @param stdClass $data
3694 * @return course_request The newly created course request
3696 public static function create($data) {
3697 global $USER, $DB, $CFG;
3698 $data->requester = $USER->id;
3700 // Summary is a required field so copy the text over
3701 $data->summary = $data->summary_editor['text'];
3702 $data->summaryformat = $data->summary_editor['format'];
3704 $data->id = $DB->insert_record('course_request', $data);
3706 // Create a new course_request object and return it
3707 $request = new course_request($data);
3709 // Notify the admin if required.
3710 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
3712 $a = new stdClass;
3713 $a->link = "$CFG->wwwroot/course/pending.php";
3714 $a->user = fullname($USER);
3715 $subject = get_string('courserequest');
3716 $message = get_string('courserequestnotifyemail', 'admin', $a);
3717 foreach ($users as $user) {
3718 $this->notify($user, $USER, 'courserequested', $subject, $message);
3722 return $request;
3726 * Returns an array of options to use with a summary editor
3728 * @uses course_request::$summaryeditoroptions
3729 * @return array An array of options to use with the editor
3731 public static function summary_editor_options() {
3732 global $CFG;
3733 if (self::$summaryeditoroptions === null) {
3734 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
3736 return self::$summaryeditoroptions;
3740 * Loads the properties for this course request object. Id is required and if
3741 * only id is provided then we load the rest of the properties from the database
3743 * @param stdClass|int $properties Either an object containing properties
3744 * or the course_request id to load
3746 public function __construct($properties) {
3747 global $DB;
3748 if (empty($properties->id)) {
3749 if (empty($properties)) {
3750 throw new coding_exception('You must provide a course request id when creating a course_request object');
3752 $id = $properties;
3753 $properties = new stdClass;
3754 $properties->id = (int)$id;
3755 unset($id);
3757 if (empty($properties->requester)) {
3758 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
3759 print_error('unknowncourserequest');
3761 } else {
3762 $this->properties = $properties;
3764 $this->properties->collision = null;
3768 * Returns the requested property
3770 * @param string $key
3771 * @return mixed
3773 public function __get($key) {
3774 return $this->properties->$key;
3778 * Override this to ensure empty($request->blah) calls return a reliable answer...
3780 * This is required because we define the __get method
3782 * @param mixed $key
3783 * @return bool True is it not empty, false otherwise
3785 public function __isset($key) {
3786 return (!empty($this->properties->$key));
3790 * Returns the user who requested this course
3792 * Uses a static var to cache the results and cut down the number of db queries
3794 * @staticvar array $requesters An array of cached users
3795 * @return stdClass The user who requested the course
3797 public function get_requester() {
3798 global $DB;
3799 static $requesters= array();
3800 if (!array_key_exists($this->properties->requester, $requesters)) {
3801 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
3803 return $requesters[$this->properties->requester];
3807 * Checks that the shortname used by the course does not conflict with any other
3808 * courses that exist
3810 * @param string|null $shortnamemark The string to append to the requests shortname
3811 * should a conflict be found
3812 * @return bool true is there is a conflict, false otherwise
3814 public function check_shortname_collision($shortnamemark = '[*]') {
3815 global $DB;
3817 if ($this->properties->collision !== null) {
3818 return $this->properties->collision;
3821 if (empty($this->properties->shortname)) {
3822 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
3823 $this->properties->collision = false;
3824 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
3825 if (!empty($shortnamemark)) {
3826 $this->properties->shortname .= ' '.$shortnamemark;
3828 $this->properties->collision = true;
3829 } else {
3830 $this->properties->collision = false;
3832 return $this->properties->collision;
3836 * This function approves the request turning it into a course
3838 * This function converts the course request into a course, at the same time
3839 * transfering any files used in the summary to the new course and then removing
3840 * the course request and the files associated with it.
3842 * @return int The id of the course that was created from this request
3844 public function approve() {
3845 global $CFG, $DB, $USER;
3847 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
3849 $category = get_course_category($CFG->defaultrequestcategory);
3850 $courseconfig = get_config('moodlecourse');
3852 // Transfer appropriate settings
3853 $data = clone($this->properties);
3854 unset($data->id);
3855 unset($data->reason);
3856 unset($data->requester);
3858 // Set category
3859 $data->category = $category->id;
3860 $data->sortorder = $category->sortorder; // place as the first in category
3862 // Set misc settings
3863 $data->requested = 1;
3864 if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
3865 $data->restrictmodules = 1;
3868 // Apply course default settings
3869 $data->format = $courseconfig->format;
3870 $data->numsections = $courseconfig->numsections;
3871 $data->hiddensections = $courseconfig->hiddensections;
3872 $data->newsitems = $courseconfig->newsitems;
3873 $data->showgrades = $courseconfig->showgrades;
3874 $data->showreports = $courseconfig->showreports;
3875 $data->maxbytes = $courseconfig->maxbytes;
3876 $data->groupmode = $courseconfig->groupmode;
3877 $data->groupmodeforce = $courseconfig->groupmodeforce;
3878 $data->visible = $courseconfig->visible;
3879 $data->visibleold = $data->visible;
3880 $data->lang = $courseconfig->lang;
3882 $course = create_course($data);
3883 $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
3885 // add enrol instances
3886 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3887 if ($manual = enrol_get_plugin('manual')) {
3888 $manual->add_default_instance($course);
3892 // enrol the requester as teacher if necessary
3893 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3894 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3897 $this->delete();
3899 $a = new object();
3900 $a->name = $course->fullname;
3901 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3902 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
3904 return $course->id;
3908 * Reject a course request
3910 * This function rejects a course request, emailing the requesting user the
3911 * provided notice and then removing the request from the database
3913 * @param string $notice The message to display to the user
3915 public function reject($notice) {
3916 global $USER, $DB;
3917 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3918 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3919 $this->delete();
3923 * Deletes the course request and any associated files
3925 public function delete() {
3926 global $DB;
3927 $DB->delete_records('course_request', array('id' => $this->properties->id));
3931 * Send a message from one user to another using events_trigger
3933 * @param object $touser
3934 * @param object $fromuser
3935 * @param string $name
3936 * @param string $subject
3937 * @param string $message
3939 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
3940 $eventdata = new object();
3941 $eventdata->modulename = 'moodle';
3942 $eventdata->component = 'course';
3943 $eventdata->name = $name;
3944 $eventdata->userfrom = $fromuser;
3945 $eventdata->userto = $touser;
3946 $eventdata->subject = $subject;
3947 $eventdata->fullmessage = $message;
3948 $eventdata->fullmessageformat = FORMAT_PLAIN;
3949 $eventdata->fullmessagehtml = '';
3950 $eventdata->smallmessage = '';
3951 message_send($eventdata);