2 // Library of useful functions
5 define('COURSE_MAX_LOG_DISPLAY', 150); // days
6 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // records
7 define('COURSE_LIVELOG_REFRESH', 60); // Seconds
8 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds
9 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10); // courses
10 define('COURSE_MAX_COURSES_PER_DROPDOWN',1000); // max courses in log dropdown before switching to optional
11 define('COURSE_MAX_USERS_PER_DROPDOWN',1000); // max users in log dropdown before switching to optional
12 define('FRONTPAGENEWS', '0');
13 define('FRONTPAGECOURSELIST', '1');
14 define('FRONTPAGECATEGORYNAMES', '2');
15 define('FRONTPAGETOPICONLY', '3');
16 define('FRONTPAGECATEGORYCOMBO', '4');
17 if (!defined('FRONTPAGECOURSELIMIT')) {
18 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
20 define('EXCELROWS', 65535);
21 define('FIRSTUSEDEXCELROW', 3);
23 define('MOD_CLASS_ACTIVITY', 0);
24 define('MOD_CLASS_RESOURCE', 1);
26 if (!defined('MAX_MODINFO_CACHE_SIZE')) {
27 define('MAX_MODINFO_CACHE_SIZE', 10);
30 function make_log_url($module, $url) {
39 if (strpos($url, '../') === 0) {
40 $url = ltrim($url, '.');
42 $url = "/course/$url";
47 $url = "/$module/$url";
57 $url = "/message/$url";
69 $url = "/mod/$module/$url";
73 //now let's sanitise urls - there might be some ugly nasties:-(
74 $parts = explode('?', $url);
75 $script = array_shift($parts);
76 if (strpos($script, 'http') === 0) {
77 $script = clean_param($script, PARAM_URL
);
79 $script = clean_param($script, PARAM_PATH
);
84 $query = implode('', $parts);
85 $query = str_replace('&', '&', $query); // both & and & are stored in db :-|
86 $parts = explode('&', $query);
88 foreach ($parts as $key=>$part) {
89 $part = urlencode(urldecode($part));
90 $part = str_replace($eq, '=', $part);
93 $query = '?'.implode('&', $parts);
96 return $script.$query;
100 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
101 $modname="", $modid=0, $modaction="", $groupid=0) {
105 // It is assumed that $date is the GMT time of midnight for that day,
106 // and so the next 86400 seconds worth of logs are printed.
108 /// Setup for group handling.
110 // TODO: I don't understand group/context/etc. enough to be able to do
111 // something interesting with it here
112 // What is the context of a remote course?
114 /// If the group mode is separate, and this user does not have editing privileges,
115 /// then only the user's group can be viewed.
116 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
117 // $groupid = get_current_group($course->id);
119 /// If this course doesn't have groups, no groupid can be specified.
120 //else if (!$course->groupmode) {
134 {$CFG->prefix}mnet_log l
142 $where .= "l.hostid = '$hostid'";
144 // TODO: Is 1 really a magic number referring to the sitename?
145 if ($course != 1 ||
$modid != 0) {
146 $where .= " AND\n l.course='$course'";
150 $where .= " AND\n l.module = '$modname'";
153 if ('site_errors' === $modid) {
154 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
156 //TODO: This assumes that modids are the same across sites... probably
158 $where .= " AND\n l.cmid = '$modid'";
162 $firstletter = substr($modaction, 0, 1);
163 if (preg_match('/[[:alpha:]]/', $firstletter)) {
164 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
165 } else if ($firstletter == '-') {
166 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
171 $where .= " AND\n l.userid = '$user'";
175 $enddate = $date +
86400;
176 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
180 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
181 if(!empty($result['totalcount'])) {
182 $where .= "\n ORDER BY\n $order";
183 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
185 $result['logs'] = array();
190 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
191 $modname="", $modid=0, $modaction="", $groupid=0) {
193 // It is assumed that $date is the GMT time of midnight for that day,
194 // and so the next 86400 seconds worth of logs are printed.
196 /// Setup for group handling.
198 /// If the group mode is separate, and this user does not have editing privileges,
199 /// then only the user's group can be viewed.
200 if ($course->groupmode
== SEPARATEGROUPS
and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
201 $groupid = get_current_group($course->id
);
203 /// If this course doesn't have groups, no groupid can be specified.
204 else if (!$course->groupmode
) {
210 if ($course->id
!= SITEID ||
$modid != 0) {
211 $joins[] = "l.course='$course->id'";
215 $joins[] = "l.module = '$modname'";
218 if ('site_errors' === $modid) {
219 $joins[] = "( l.action='error' OR l.action='infected' )";
221 $joins[] = "l.cmid = '$modid'";
225 $firstletter = substr($modaction, 0, 1);
226 if (preg_match('/[[:alpha:]]/', $firstletter)) {
227 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
228 } else if ($firstletter == '-') {
229 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
234 /// Getting all members of a group.
235 if ($groupid and !$user) {
236 if ($gusers = groups_get_members($groupid)) {
237 $gusers = array_keys($gusers);
238 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
240 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
244 $joins[] = "l.userid = '$user'";
248 $enddate = $date +
86400;
249 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
252 $selector = implode(' AND ', $joins);
254 $totalcount = 0; // Initialise
256 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
257 $result['totalcount'] = $totalcount;
262 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
263 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
267 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
268 $modname, $modid, $modaction, $groupid)) {
269 notify("No logs found!");
270 print_footer($course);
276 if ($course->id
== SITEID
) {
278 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
279 foreach ($ccc as $cc) {
280 $courses[$cc->id
] = $cc->shortname
;
284 $courses[$course->id
] = $course->shortname
;
287 $totalcount = $logs['totalcount'];
290 $tt = getdate(time());
291 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
293 $strftimedatetime = get_string("strftimedatetime");
295 echo "<div class=\"info\">\n";
296 print_string("displayingrecords", "", $totalcount);
299 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
301 echo '<table class="logtable generalbox boxaligncenter" summary="">'."\n";
302 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
304 if ($course->id
== SITEID
) {
305 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
307 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
308 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
309 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
310 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
311 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
314 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
315 if (empty($logs['logs'])) {
316 $logs['logs'] = array();
320 foreach ($logs['logs'] as $log) {
322 $row = ($row +
1) %
2;
324 if (isset($ldcache[$log->module
][$log->action
])) {
325 $ld = $ldcache[$log->module
][$log->action
];
327 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
328 $ldcache[$log->module
][$log->action
] = $ld;
330 if ($ld && is_numeric($log->info
)) {
331 // ugly hack to make sure fullname is shown correctly
332 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
333 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
335 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
340 $log->info
= format_string($log->info
);
342 // If $log->url has been trimmed short by the db size restriction
343 // code in add_to_log, keep a note so we don't add a link to a broken url
344 $tl=textlib_get_instance();
345 $brokenurl=($tl->strlen($log->url
)==100 && $tl->substr($log->url
,97)=='...');
347 echo '<tr class="r'.$row.'">';
348 if ($course->id
== SITEID
) {
349 echo "<td class=\"cell c0\">\n";
350 if (empty($log->course
)) {
351 echo get_string('site') . "\n";
353 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course
])."</a>\n";
357 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time
, '%a').
358 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
359 echo "<td class=\"cell c2\">\n";
360 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 440, 700);
362 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
363 echo "<td class=\"cell c3\">\n";
364 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&course={$log->course}\">$fullname</a>\n";
366 echo "<td class=\"cell c4\">\n";
367 $displayaction="$log->module $log->action";
371 link_to_popup_window( make_log_url($log->module
,$log->url
), 'fromloglive',$displayaction, 440, 700);
374 echo "<td class=\"cell c5\">{$log->info}</td>\n";
379 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
383 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
384 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
388 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
389 $modname, $modid, $modaction, $groupid)) {
390 notify("No logs found!");
391 print_footer($course);
395 if ($course->id
== SITEID
) {
397 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
398 foreach ($ccc as $cc) {
399 $courses[$cc->id
] = $cc->shortname
;
404 $totalcount = $logs['totalcount'];
407 $tt = getdate(time());
408 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
410 $strftimedatetime = get_string("strftimedatetime");
412 echo "<div class=\"info\">\n";
413 print_string("displayingrecords", "", $totalcount);
416 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
418 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
420 if ($course->id
== SITEID
) {
421 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
423 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
424 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
425 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
426 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
427 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
430 if (empty($logs['logs'])) {
436 foreach ($logs['logs'] as $log) {
438 $log->info
= $log->coursename
;
439 $row = ($row +
1) %
2;
441 if (isset($ldcache[$log->module
][$log->action
])) {
442 $ld = $ldcache[$log->module
][$log->action
];
444 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
445 $ldcache[$log->module
][$log->action
] = $ld;
447 if (0 && $ld && !empty($log->info
)) {
448 // ugly hack to make sure fullname is shown correctly
449 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
450 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
452 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
457 $log->info
= format_string($log->info
);
459 echo '<tr class="r'.$row.'">';
460 if ($course->id
== SITEID
) {
461 echo "<td class=\"r$row c0\" >\n";
462 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course
]."</a>\n";
465 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time
, '%a').
466 ' '.userdate($log->time
, $strftimedatetime)."</td>\n";
467 echo "<td class=\"r$row c2\" >\n";
468 link_to_popup_window("/iplookup/index.php?ip=$log->ip&user=$log->userid", 'iplookup',$log->ip
, 400, 700);
470 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
471 echo "<td class=\"r$row c3\" >\n";
472 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
474 echo "<td class=\"r$row c4\">\n";
475 echo $log->action
.': '.$log->module
;
477 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
482 print_paging_bar($totalcount, $page, $perpage, "$url&perpage=$perpage&");
486 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
487 $modid, $modaction, $groupid) {
489 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
490 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
492 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
493 $modname, $modid, $modaction, $groupid)) {
499 if ($course->id
== SITEID
) {
501 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
502 foreach ($ccc as $cc) {
503 $courses[$cc->id
] = $cc->shortname
;
507 $courses[$course->id
] = $course->shortname
;
512 $tt = getdate(time());
513 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
515 $strftimedatetime = get_string("strftimedatetime");
517 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
519 header("Content-Type: application/download\n");
520 header("Content-Disposition: attachment; filename=$filename");
521 header("Expires: 0");
522 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
523 header("Pragma: public");
525 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
528 if (empty($logs['logs'])) {
532 foreach ($logs['logs'] as $log) {
533 if (isset($ldcache[$log->module
][$log->action
])) {
534 $ld = $ldcache[$log->module
][$log->action
];
536 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
537 $ldcache[$log->module
][$log->action
] = $ld;
539 if ($ld && !empty($log->info
)) {
540 // ugly hack to make sure fullname is shown correctly
541 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
542 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
544 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
549 $log->info
= format_string($log->info
);
550 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
552 $firstField = $courses[$log->course
];
553 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
554 $row = array($firstField, userdate($log->time
, $strftimedatetime), $log->ip
, $fullname, $log->module
.' '.$log->action
, $log->info
);
555 $text = implode("\t", $row);
562 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
563 $modid, $modaction, $groupid) {
567 require_once("$CFG->libdir/excellib.class.php");
569 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
570 $modname, $modid, $modaction, $groupid)) {
576 if ($course->id
== SITEID
) {
578 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
579 foreach ($ccc as $cc) {
580 $courses[$cc->id
] = $cc->shortname
;
584 $courses[$course->id
] = $course->shortname
;
589 $tt = getdate(time());
590 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
592 $strftimedatetime = get_string("strftimedatetime");
594 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
595 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
598 $workbook = new MoodleExcelWorkbook('-');
599 $workbook->send($filename);
601 $worksheet = array();
602 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
603 get_string('fullname'), get_string('action'), get_string('info'));
605 // Creating worksheets
606 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
607 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
608 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
609 $worksheet[$wsnumber]->set_column(1, 1, 30);
610 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
611 userdate(time(), $strftimedatetime));
613 foreach ($headers as $item) {
614 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
619 if (empty($logs['logs'])) {
624 $formatDate =& $workbook->add_format();
625 $formatDate->set_num_format(get_string('log_excel_date_format'));
627 $row = FIRSTUSEDEXCELROW
;
629 $myxls =& $worksheet[$wsnumber];
630 foreach ($logs['logs'] as $log) {
631 if (isset($ldcache[$log->module
][$log->action
])) {
632 $ld = $ldcache[$log->module
][$log->action
];
634 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
635 $ldcache[$log->module
][$log->action
] = $ld;
637 if ($ld && !empty($log->info
)) {
638 // ugly hack to make sure fullname is shown correctly
639 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
640 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
642 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
647 $log->info
= format_string($log->info
);
648 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
651 if ($row > EXCELROWS
) {
653 $myxls =& $worksheet[$wsnumber];
654 $row = FIRSTUSEDEXCELROW
;
658 $myxls->write($row, 0, $courses[$log->course
], '');
659 $myxls->write_date($row, 1, $log->time
, $formatDate); // write_date() does conversion/timezone support. MDL-14934
660 $myxls->write($row, 2, $log->ip
, '');
661 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
662 $myxls->write($row, 3, $fullname, '');
663 $myxls->write($row, 4, $log->module
.' '.$log->action
, '');
664 $myxls->write($row, 5, $log->info
, '');
673 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
674 $modid, $modaction, $groupid) {
678 require_once("$CFG->libdir/odslib.class.php");
680 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
681 $modname, $modid, $modaction, $groupid)) {
687 if ($course->id
== SITEID
) {
689 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
690 foreach ($ccc as $cc) {
691 $courses[$cc->id
] = $cc->shortname
;
695 $courses[$course->id
] = $course->shortname
;
700 $tt = getdate(time());
701 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
703 $strftimedatetime = get_string("strftimedatetime");
705 $nroPages = ceil(count($logs)/(EXCELROWS
-FIRSTUSEDEXCELROW+
1));
706 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
709 $workbook = new MoodleODSWorkbook('-');
710 $workbook->send($filename);
712 $worksheet = array();
713 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
714 get_string('fullname'), get_string('action'), get_string('info'));
716 // Creating worksheets
717 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++
) {
718 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
719 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
720 $worksheet[$wsnumber]->set_column(1, 1, 30);
721 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
722 userdate(time(), $strftimedatetime));
724 foreach ($headers as $item) {
725 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW
-1,$col,$item,'');
730 if (empty($logs['logs'])) {
735 $formatDate =& $workbook->add_format();
736 $formatDate->set_num_format(get_string('log_excel_date_format'));
738 $row = FIRSTUSEDEXCELROW
;
740 $myxls =& $worksheet[$wsnumber];
741 foreach ($logs['logs'] as $log) {
742 if (isset($ldcache[$log->module
][$log->action
])) {
743 $ld = $ldcache[$log->module
][$log->action
];
745 $ld = get_record('log_display', 'module', $log->module
, 'action', $log->action
);
746 $ldcache[$log->module
][$log->action
] = $ld;
748 if ($ld && !empty($log->info
)) {
749 // ugly hack to make sure fullname is shown correctly
750 if (($ld->mtable
== 'user') and ($ld->field
== sql_concat('firstname', "' '" , 'lastname'))) {
751 $log->info
= fullname(get_record($ld->mtable
, 'id', $log->info
), true);
753 $log->info
= get_field($ld->mtable
, $ld->field
, 'id', $log->info
);
758 $log->info
= format_string($log->info
);
759 $log->info
= strip_tags(urldecode($log->info
)); // Some XSS protection
762 if ($row > EXCELROWS
) {
764 $myxls =& $worksheet[$wsnumber];
765 $row = FIRSTUSEDEXCELROW
;
769 $myxls->write_string($row, 0, $courses[$log->course
]);
770 $myxls->write_date($row, 1, $log->time
);
771 $myxls->write_string($row, 2, $log->ip
);
772 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE
, $course->id
)));
773 $myxls->write_string($row, 3, $fullname);
774 $myxls->write_string($row, 4, $log->module
.' '.$log->action
);
775 $myxls->write_string($row, 5, $log->info
);
785 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
787 if (empty($CFG->gdversion
)) {
788 echo "(".get_string("gdneed").")";
790 // MDL-10818, do not display broken graph when user has no permission to view graph
791 if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE
, $course->id
)) ||
792 ($course->showreports
and $USER->id
== $userid)) {
793 echo '<img src="'.$CFG->wwwroot
.'/course/report/log/graph.php?id='.$course->id
.
794 '&user='.$userid.'&type='.$type.'&date='.$date.'" alt="" />';
800 function print_overview($courses) {
804 $htmlarray = array();
805 if ($modules = get_records('modules')) {
806 foreach ($modules as $mod) {
807 if (file_exists(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php')) {
808 include_once(dirname(dirname(__FILE__
)).'/mod/'.$mod->name
.'/lib.php');
809 $fname = $mod->name
.'_print_overview';
810 if (function_exists($fname)) {
811 $fname($courses,$htmlarray);
816 foreach ($courses as $course) {
817 print_simple_box_start('center', '100%', '', 5, "coursebox");
819 if (empty($course->visible
)) {
820 $linkcss = 'class="dimmed"';
822 print_heading('<a title="'. format_string($course->fullname
).'" '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>');
823 if (array_key_exists($course->id
,$htmlarray)) {
824 foreach ($htmlarray[$course->id
] as $modname => $html) {
828 print_simple_box_end();
833 function print_recent_activity($course) {
834 // $course is an object
835 // This function trawls through the logs looking for
836 // anything new since the user's last login
838 global $CFG, $USER, $SESSION;
840 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
842 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
844 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD
, -2); // better db caching for guests - 100 seconds
846 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
847 if (!empty($USER->lastcourseaccess
[$course->id
])) {
848 if ($USER->lastcourseaccess
[$course->id
] > $timestart) {
849 $timestart = $USER->lastcourseaccess
[$course->id
];
854 echo '<div class="activitydate">';
855 echo get_string('activitysince', '', userdate($timestart));
857 echo '<div class="activityhead">';
859 echo '<a href="'.$CFG->wwwroot
.'/course/recent.php?id='.$course->id
.'">'.get_string('recentactivityreport').'</a>';
865 /// Firstly, have there been any new enrolments?
867 $users = get_recent_enrolments($course->id
, $timestart);
869 //Accessibility: new users now appear in an <OL> list.
871 echo '<div class="newusers">';
872 print_headline(get_string("newusers").':', 3);
874 echo "<ol class=\"list\">\n";
875 foreach ($users as $user) {
876 $fullname = fullname($user, $viewfullnames);
877 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id\">$fullname</a></li>\n";
879 echo "</ol>\n</div>\n";
882 /// Next, have there been any modifications to the course structure?
884 $modinfo =& get_fast_modinfo($course);
886 $changelist = array();
888 $logs = get_records_select('log', "time > $timestart AND course = $course->id AND
889 module = 'course' AND
890 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
894 $actions = array('add mod', 'update mod', 'delete mod');
895 $newgones = array(); // added and later deleted items
896 foreach ($logs as $key => $log) {
897 if (!in_array($log->action
, $actions)) {
900 $info = split(' ', $log->info
);
902 if ($info[0] == 'label') { // Labels are ignored in recent activity
906 if (count($info) != 2) {
907 debugging("Incorrect log entry info: id = ".$log->id
, DEBUG_DEVELOPER
);
912 $instanceid = $info[1];
914 if ($log->action
== 'delete mod') {
915 // unfortunately we do not know if the mod was visible
916 if (!array_key_exists($log->info
, $newgones)) {
917 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
918 $changelist[$log->info
] = array ('operation' => 'delete', 'text' => $strdeleted);
921 if (!isset($modinfo->instances
[$modname][$instanceid])) {
922 if ($log->action
== 'add mod') {
923 // do not display added and later deleted activities
924 $newgones[$log->info
] = true;
928 $cm = $modinfo->instances
[$modname][$instanceid];
929 if (!$cm->uservisible
) {
933 if ($log->action
== 'add mod') {
934 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
935 $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>");
937 } else if ($log->action
== 'update mod' and empty($changelist[$log->info
])) {
938 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
939 $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>");
945 if (!empty($changelist)) {
946 print_headline(get_string('courseupdates').':', 3);
948 foreach ($changelist as $changeinfo => $change) {
949 echo '<p class="activity">'.$change['text'].'</p>';
953 /// Now display new things from each module
955 $usedmodules = array();
956 foreach($modinfo->cms
as $cm) {
957 if (isset($usedmodules[$cm->modname
])) {
960 if (!$cm->uservisible
) {
963 $usedmodules[$cm->modname
] = $cm->modname
;
966 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
967 if (file_exists($CFG->dirroot
.'/mod/'.$modname.'/lib.php')) {
968 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
969 $print_recent_activity = $modname.'_print_recent_activity';
970 if (function_exists($print_recent_activity)) {
971 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
972 $content = $print_recent_activity($course, $viewfullnames, $timestart) ||
$content;
975 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
980 echo '<p class="message">'.get_string('nothingnew').'</p>';
985 function get_array_of_activities($courseid) {
986 // For a given course, returns an array of course activity objects
987 // Each item in the array contains he following properties:
988 // cm - course module id
989 // mod - name of the module (eg forum)
990 // section - the number of the section (eg week or topic)
991 // name - the name of the instance
992 // visible - is the instance visible or not
993 // groupingid - grouping id
994 // groupmembersonly - is this instance visible to group members only
995 // extra - contains extra string to include in any link
1001 if (!$rawmods = get_course_mods($courseid)) {
1002 return $mod; // always return array
1005 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
1006 foreach ($sections as $section) {
1007 if (!empty($section->sequence
)) {
1008 $sequence = explode(",", $section->sequence
);
1009 foreach ($sequence as $seq) {
1010 if (empty($rawmods[$seq])) {
1013 $mod[$seq]->id
= $rawmods[$seq]->instance
;
1014 $mod[$seq]->cm
= $rawmods[$seq]->id
;
1015 $mod[$seq]->mod
= $rawmods[$seq]->modname
;
1016 $mod[$seq]->section
= $section->section
;
1017 $mod[$seq]->visible
= $rawmods[$seq]->visible
;
1018 $mod[$seq]->groupmode
= $rawmods[$seq]->groupmode
;
1019 $mod[$seq]->groupingid
= $rawmods[$seq]->groupingid
;
1020 $mod[$seq]->groupmembersonly
= $rawmods[$seq]->groupmembersonly
;
1021 $mod[$seq]->extra
= "";
1023 $modname = $mod[$seq]->mod
;
1024 $functionname = $modname."_get_coursemodule_info";
1026 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
1030 include_once("$CFG->dirroot/mod/$modname/lib.php");
1032 if (function_exists($functionname)) {
1033 if ($info = $functionname($rawmods[$seq])) {
1034 if (!empty($info->extra
)) {
1035 $mod[$seq]->extra
= $info->extra
;
1037 if (!empty($info->icon
)) {
1038 $mod[$seq]->icon
= $info->icon
;
1040 if (!empty($info->name
)) {
1041 $mod[$seq]->name
= urlencode($info->name
);
1045 if (!isset($mod[$seq]->name
)) {
1046 $mod[$seq]->name
= urlencode(get_field($rawmods[$seq]->modname
, "name", "id", $rawmods[$seq]->instance
));
1057 * Returns reference to full info about modules in course (including visibility).
1058 * Cached and as fast as possible (0 or 1 db query).
1059 * @param $course object or 'reset' string to reset caches, modinfo may be updated in db
1060 * @return mixed courseinfo object or nothing if resetting
1062 function &get_fast_modinfo(&$course, $userid=0) {
1065 static $cache = array();
1067 if ($course === 'reset') {
1070 return $nothing; // we must return some reference
1073 if (empty($userid)) {
1074 $userid = $USER->id
;
1077 if (array_key_exists($course->id
, $cache) and $cache[$course->id
]->userid
== $userid) {
1078 return $cache[$course->id
];
1081 if (empty($course->modinfo
)) {
1082 // no modinfo yet - load it
1083 rebuild_course_cache($course->id
);
1084 $course->modinfo
= get_field('course', 'modinfo', 'id', $course->id
);
1087 $modinfo = new object();
1088 $modinfo->courseid
= $course->id
;
1089 $modinfo->userid
= $userid;
1090 $modinfo->sections
= array();
1091 $modinfo->cms
= array();
1092 $modinfo->instances
= array();
1093 $modinfo->groups
= null; // loaded only when really needed - the only one db query
1095 $info = unserialize($course->modinfo
);
1096 if (!is_array($info)) {
1097 // hmm, something is wrong - lets try to fix it
1098 rebuild_course_cache($course->id
);
1099 $course->modinfo
= get_field('course', 'modinfo', 'id', $course->id
);
1100 $info = unserialize($course->modinfo
);
1101 if (!is_array($info)) {
1107 // detect if upgrade required
1108 $first = reset($info);
1109 if (!isset($first->id
)) {
1110 rebuild_course_cache($course->id
);
1111 $course->modinfo
= get_field('course', 'modinfo', 'id', $course->id
);
1112 $info = unserialize($course->modinfo
);
1113 if (!is_array($info)) {
1119 $modlurals = array();
1121 // If we haven't already preloaded contexts for the course, do it now
1122 preload_course_contexts($course->id
);
1124 foreach ($info as $mod) {
1125 if (empty($mod->name
)) {
1126 // something is wrong here
1129 // reconstruct minimalistic $cm
1132 $cm->instance
= $mod->id
;
1133 $cm->course
= $course->id
;
1134 $cm->modname
= $mod->mod
;
1135 $cm->name
= urldecode($mod->name
);
1136 $cm->visible
= $mod->visible
;
1137 $cm->sectionnum
= $mod->section
;
1138 $cm->groupmode
= $mod->groupmode
;
1139 $cm->groupingid
= $mod->groupingid
;
1140 $cm->groupmembersonly
= $mod->groupmembersonly
;
1141 $cm->extra
= isset($mod->extra
) ?
urldecode($mod->extra
) : '';
1142 $cm->icon
= isset($mod->icon
) ?
$mod->icon
: '';
1143 $cm->uservisible
= true;
1145 // preload long names plurals and also check module is installed properly
1146 if (!isset($modlurals[$cm->modname
])) {
1147 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
1150 $modlurals[$cm->modname
] = get_string('modulenameplural', $cm->modname
);
1152 $cm->modplural
= $modlurals[$cm->modname
];
1154 $modcontext = get_context_instance(CONTEXT_MODULE
,$cm->id
);
1156 if (!$cm->visible
and !has_capability('moodle/course:viewhiddenactivities',
1157 $modcontext, $userid)) {
1158 $cm->uservisible
= false;
1160 } else if (!empty($CFG->enablegroupings
) and !empty($cm->groupmembersonly
)
1161 and !has_capability('moodle/site:accessallgroups', $modcontext, $userid)) {
1162 if (is_null($modinfo->groups
)) {
1163 $modinfo->groups
= groups_get_user_groups($course->id
, $userid);
1165 if (empty($modinfo->groups
[$cm->groupingid
])) {
1166 $cm->uservisible
= false;
1170 if (!isset($modinfo->instances
[$cm->modname
])) {
1171 $modinfo->instances
[$cm->modname
] = array();
1173 $modinfo->instances
[$cm->modname
][$cm->instance
] =& $cm;
1174 $modinfo->cms
[$cm->id
] =& $cm;
1176 // reconstruct sections
1177 if (!isset($modinfo->sections
[$cm->sectionnum
])) {
1178 $modinfo->sections
[$cm->sectionnum
] = array();
1180 $modinfo->sections
[$cm->sectionnum
][] = $cm->id
;
1185 unset($cache[$course->id
]); // prevent potential reference problems when switching users
1186 $cache[$course->id
] = $modinfo;
1188 // Ensure cache does not use too much RAM
1189 if (count($cache) > MAX_MODINFO_CACHE_SIZE
) {
1192 unset($cache[$key]);
1195 return $cache[$course->id
];
1199 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1200 // Returns a number of useful structures for course displays
1202 $mods = array(); // course modules indexed by id
1203 $modnames = array(); // all course module names (except resource!)
1204 $modnamesplural= array(); // all course module names (plural form)
1205 $modnamesused = array(); // course module names used
1207 if ($allmods = get_records("modules")) {
1208 foreach ($allmods as $mod) {
1209 if ($mod->visible
) {
1210 $modnames[$mod->name
] = get_string("modulename", "$mod->name");
1211 $modnamesplural[$mod->name
] = get_string("modulenameplural", "$mod->name");
1214 asort($modnames, SORT_LOCALE_STRING
);
1216 error("No modules are installed!");
1219 if ($rawmods = get_course_mods($courseid)) {
1220 foreach($rawmods as $mod) { // Index the mods
1221 if (empty($modnames[$mod->modname
])) {
1224 $mods[$mod->id
] = $mod;
1225 $mods[$mod->id
]->modfullname
= $modnames[$mod->modname
];
1226 if (!$mod->visible
and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $courseid))) {
1230 if (!groups_course_module_visible($mod)) {
1233 $modnamesused[$mod->modname
] = $modnames[$mod->modname
];
1235 if ($modnamesused) {
1236 asort($modnamesused, SORT_LOCALE_STRING
);
1242 function get_all_sections($courseid) {
1244 return get_records("course_sections", "course", "$courseid", "section",
1245 "section, id, course, summary, sequence, visible");
1248 function course_set_display($courseid, $display=0) {
1251 if ($display == "all" or empty($display)) {
1255 if (empty($USER->id
) or $USER->username
== 'guest') {
1256 //do not store settings in db for guests
1257 } else if (record_exists("course_display", "userid", $USER->id
, "course", $courseid)) {
1258 set_field("course_display", "display", $display, "userid", $USER->id
, "course", $courseid);
1260 $record = new object();
1261 $record->userid
= $USER->id
;
1262 $record->course
= $courseid;
1263 $record->display
= $display;
1264 if (!insert_record("course_display", $record)) {
1265 notify("Could not save your course display!");
1269 return $USER->display
[$courseid] = $display; // Note: = not ==
1272 function set_section_visible($courseid, $sectionnumber, $visibility) {
1273 /// For a given course section, markes it visible or hidden,
1274 /// and does the same for every activity in that section
1276 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1277 set_field("course_sections", "visible", "$visibility", "id", $section->id
);
1278 if (!empty($section->sequence
)) {
1279 $modules = explode(",", $section->sequence
);
1280 foreach ($modules as $moduleid) {
1281 set_coursemodule_visible($moduleid, $visibility, true);
1284 rebuild_course_cache($courseid);
1289 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1290 /// Prints a section full of activity modules
1293 static $initialised;
1295 static $groupbuttons;
1296 static $groupbuttonslink;
1299 static $strmovehere;
1300 static $strmovefull;
1301 static $strunreadpostsone;
1302 static $usetracking;
1306 if (!isset($initialised)) {
1307 $groupbuttons = ($course->groupmode
or (!$course->groupmodeforce
));
1308 $groupbuttonslink = (!$course->groupmodeforce
);
1309 $isediting = isediting($course->id
);
1310 $ismoving = $isediting && ismoving($course->id
);
1312 $strmovehere = get_string("movehere");
1313 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1315 include_once($CFG->dirroot
.'/mod/forum/lib.php');
1316 if ($usetracking = forum_tp_can_track_forums()) {
1317 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1319 $initialised = true;
1322 $labelformatoptions = new object();
1323 $labelformatoptions->noclean
= true;
1325 /// Casting $course->modinfo to string prevents one notice when the field is null
1326 $modinfo = get_fast_modinfo($course);
1329 //Acccessibility: replace table with list <ul>, but don't output empty list.
1330 if (!empty($section->sequence
)) {
1332 // Fix bug #5027, don't want style=\"width:$width\".
1333 echo "<ul class=\"section img-text\">\n";
1334 $sectionmods = explode(",", $section->sequence
);
1336 foreach ($sectionmods as $modnumber) {
1337 if (empty($mods[$modnumber])) {
1341 $mod = $mods[$modnumber];
1343 if ($ismoving and $mod->id
== $USER->activitycopy
) {
1344 // do not display moving mod
1348 if (isset($modinfo->cms
[$modnumber])) {
1349 if (!$modinfo->cms
[$modnumber]->uservisible
) {
1350 // visibility shortcut
1354 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1355 // module not installed
1358 if (!coursemodule_visible_for_user($mod)) {
1359 // full visibility check
1364 echo '<li class="activity '.$mod->modname
.'" id="module-'.$modnumber.'">'; // Unique ID
1366 echo '<a title="'.$strmovefull.'"'.
1367 ' href="'.$CFG->wwwroot
.'/course/mod.php?moveto='.$mod->id
.'&sesskey='.$USER->sesskey
.'">'.
1368 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1369 ' alt="'.$strmovehere.'" /></a><br />
1374 print_spacer(12, 20 * $mod->indent
, false);
1378 if (!empty($modinfo->cms
[$modnumber]->extra
)) {
1379 $extra = $modinfo->cms
[$modnumber]->extra
;
1382 if ($mod->modname
== "label") {
1383 echo "<span class=\"";
1384 if (!$mod->visible
) {
1390 echo format_text($extra, FORMAT_HTML
, $labelformatoptions);
1392 if (!empty($CFG->enablegroupings
) && !empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1393 if (!isset($groupings)) {
1394 $groupings = groups_get_all_groupings($course->id
);
1396 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1399 } else { // Normal activity
1400 $instancename = format_string($modinfo->cms
[$modnumber]->name
, true, $course->id
);
1402 if (!empty($modinfo->cms
[$modnumber]->icon
)) {
1403 $icon = "$CFG->pixpath/".$modinfo->cms
[$modnumber]->icon
;
1405 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1408 //Accessibility: for files get description via icon.
1410 if ('resource'==$mod->modname
) {
1411 if (!empty($modinfo->cms
[$modnumber]->icon
)) {
1412 $possaltname = $modinfo->cms
[$modnumber]->icon
;
1414 $mimetype = mimeinfo_from_icon('type', $possaltname);
1415 $altname = get_mimetype_description($mimetype);
1417 $altname = $mod->modfullname
;
1420 $altname = $mod->modfullname
;
1422 // Avoid unnecessary duplication.
1423 if (false!==stripos($instancename, $altname)) {
1426 // File type after name, for alphabetic lists (screen reader).
1428 $altname = get_accesshide(' '.$altname);
1431 $linkcss = $mod->visible ?
"" : " class=\"dimmed\" ";
1432 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1433 ' href="'.$CFG->wwwroot
.'/mod/'.$mod->modname
.'/view.php?id='.$mod->id
.'">'.
1434 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1435 $instancename.$altname.'</span></a>';
1437 if (!empty($CFG->enablegroupings
) && !empty($mod->groupingid
) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1438 if (!isset($groupings)) {
1439 $groupings = groups_get_all_groupings($course->id
);
1441 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid
]->name
).')</span>';
1444 if ($usetracking && $mod->modname
== 'forum') {
1445 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1446 echo '<span class="unread"> <a href="'.$CFG->wwwroot
.'/mod/forum/view.php?id='.$mod->id
.'">';
1448 echo $strunreadpostsone;
1450 print_string('unreadpostsnumber', 'forum', $unread);
1457 // TODO: we must define this as mod property!
1458 if ($groupbuttons and $mod->modname
!= 'label' and $mod->modname
!= 'resource' and $mod->modname
!= 'glossary') {
1459 if (! $mod->groupmodelink
= $groupbuttonslink) {
1460 $mod->groupmode
= $course->groupmode
;
1464 $mod->groupmode
= false;
1466 echo ' ';
1467 echo make_editing_buttons($mod, $absolute, true, $mod->indent
, $section->section
);
1472 } elseif ($ismoving) {
1473 echo "<ul class=\"section\">\n";
1477 echo '<li><a title="'.$strmovefull.'"'.
1478 ' href="'.$CFG->wwwroot
.'/course/mod.php?movetosection='.$section->id
.'&sesskey='.$USER->sesskey
.'">'.
1479 '<img class="movetarget" src="'.$CFG->pixpath
.'/movehere.gif" '.
1480 ' alt="'.$strmovehere.'" /></a></li>
1483 if (!empty($section->sequence
) ||
$ismoving) {
1484 echo "</ul><!--class='section'-->\n\n";
1489 * Prints the menus to add activities and resources.
1491 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1494 // check to see if user can add menus
1495 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1499 static $resources = false;
1500 static $activities = false;
1502 if ($resources === false) {
1503 $resources = array();
1504 $activities = array();
1506 foreach($modnames as $modname=>$modnamestr) {
1507 if (!course_allowed_module($course, $modname)) {
1511 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1512 if (!file_exists($libfile)) {
1515 include_once($libfile);
1516 $gettypesfunc = $modname.'_get_types';
1517 if (function_exists($gettypesfunc)) {
1518 $types = $gettypesfunc();
1519 foreach($types as $type) {
1520 if (!isset($type->modclass
) or !isset($type->typestr
)) {
1521 debugging('Incorrect activity type in '.$modname);
1524 if ($type->modclass
== MOD_CLASS_RESOURCE
) {
1525 $resources[$type->type
] = $type->typestr
;
1527 $activities[$type->type
] = $type->typestr
;
1531 // all mods without type are considered activity
1532 $activities[$modname] = $modnamestr;
1537 $straddactivity = get_string('addactivity');
1538 $straddresource = get_string('addresource');
1540 $output = '<div class="section_add_menus">';
1543 $output .= '<div class="horizontal">';
1546 if (!empty($resources)) {
1547 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1548 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1551 if (!empty($activities)) {
1553 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&section=$section&sesskey=".sesskey()."&add=",
1554 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1558 $output .= '</div>';
1561 $output .= '</div>';
1571 * Return the course category context for the category with id $categoryid, except
1572 * that if $categoryid is 0, return the system context.
1574 * @param integer $categoryid a category id or 0.
1575 * @return object the corresponding context
1577 function get_category_or_system_context($categoryid) {
1579 return get_context_instance(CONTEXT_COURSECAT
, $categoryid);
1581 return get_context_instance(CONTEXT_SYSTEM
);
1586 * Rebuilds the cached list of course activities stored in the database
1587 * @param int $courseid - id of course to rebuil, empty means all
1588 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1590 function rebuild_course_cache($courseid=0, $clearonly=false) {
1594 $courseselect = empty($courseid) ?
"" : "id = $courseid";
1595 set_field_select('course', 'modinfo', null, $courseselect);
1596 // update cached global COURSE too ;-)
1597 if ($courseid == $COURSE->id
) {
1598 $COURSE->modinfo
= null;
1600 // reset the fast modinfo cache
1602 get_fast_modinfo($reset);
1607 $select = "id = '$courseid'";
1610 @set_time_limit
(0); // this could take a while! MDL-10954
1613 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1614 while($course = rs_fetch_next_record($rs)) {
1615 $modinfo = serialize(get_array_of_activities($course->id
));
1616 if (!set_field("course", "modinfo", $modinfo, "id", $course->id
)) {
1617 notify("Could not cache module information for course '" . format_string($course->fullname
) . "'!");
1619 // update cached global COURSE too ;-)
1620 if ($course->id
== $COURSE->id
) {
1621 $COURSE->modinfo
= $modinfo;
1626 // reset the fast modinfo cache
1628 get_fast_modinfo($reset);
1632 * Gets the child categories of a given coures category. Uses a static cache
1633 * to make repeat calls efficient.
1635 * @param unknown_type $parentid the id of a course category.
1636 * @return array all the child course categories.
1638 function get_child_categories($parentid) {
1639 static $allcategories = null;
1641 // only fill in this variable the first time
1642 if (null == $allcategories) {
1643 $allcategories = array();
1645 $categories = get_categories();
1646 foreach ($categories as $category) {
1647 if (empty($allcategories[$category->parent
])) {
1648 $allcategories[$category->parent
] = array();
1650 $allcategories[$category->parent
][] = $category;
1654 if (empty($allcategories[$parentid])) {
1657 return $allcategories[$parentid];
1662 * This function recursively travels the categories, building up a nice list
1663 * for display. It also makes an array that list all the parents for each
1666 * For example, if you have a tree of categories like:
1667 * Miscellaneous (id = 1)
1668 * Subcategory (id = 2)
1669 * Sub-subcategory (id = 4)
1670 * Other category (id = 3)
1671 * Then after calling this function you will have
1672 * $list = array(1 => 'Miscellaneous', 2 => 'Miscellaneous / Subcategory',
1673 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1674 * 3 => 'Other category');
1675 * $parents = array(2 => array(1), 4 => array(1, 2));
1677 * If you specify $requiredcapability, then only categories where the current
1678 * user has that capability will be added to $list, although all categories
1679 * will still be added to $parents, and if you only have $requiredcapability
1680 * in a child category, not the parent, then the child catgegory will still be
1683 * If you specify the option $excluded, then that category, and all its children,
1684 * are omitted from the tree. This is useful when you are doing something like
1685 * moving categories, where you do not want to allow people to move a category
1686 * to be the child of itself.
1688 * @param array $list For output, accumulates an array categoryid => full category path name
1689 * @param array $parents For output, accumulates an array categoryid => list of parent category ids.
1690 * @param string/array $requiredcapability if given, only categories where the current
1691 * user has this capability will be added to $list. Can also be an array of capabilities,
1692 * in which case they are all required.
1693 * @param integer $excludeid Omit this category and its children from the lists built.
1694 * @param object $category Build the tree starting at this category - otherwise starts at the top level.
1695 * @param string $path For internal use, as part of recursive calls.
1697 function make_categories_list(&$list, &$parents, $requiredcapability = '',
1698 $excludeid = 0, $category = NULL, $path = "") {
1700 // initialize the arrays if needed
1701 if (!is_array($list)) {
1704 if (!is_array($parents)) {
1708 if (empty($category)) {
1709 // Start at the top level.
1710 $category = new stdClass
;
1713 // This is the excluded category, don't include it.
1714 if ($excludeid > 0 && $excludeid == $category->id
) {
1720 $path = $path.' / '.format_string($category->name
);
1722 $path = format_string($category->name
);
1725 // Add this category to $list, if the permissions check out.
1726 if (empty($requiredcapability)) {
1727 $list[$category->id
] = $path;
1730 ensure_context_subobj_present($category, CONTEXT_COURSECAT
);
1731 $requiredcapability = (array)$requiredcapability;
1732 if (has_all_capabilities($requiredcapability, $category->context
)) {
1733 $list[$category->id
] = $path;
1738 // Add all the children recursively, while updating the parents array.
1739 if ($categories = get_child_categories($category->id
)) {
1740 foreach ($categories as $cat) {
1741 if (!empty($category->id
)) {
1742 if (isset($parents[$category->id
])) {
1743 $parents[$cat->id
] = $parents[$category->id
];
1745 $parents[$cat->id
][] = $category->id
;
1747 make_categories_list($list, $parents, $requiredcapability, $excludeid, $cat, $path);
1752 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $showcourses = true) {
1753 /// Recursive function to print out all the categories in a nice format
1754 /// with or without courses included
1757 // maxcategorydepth == 0 meant no limit
1758 if (!empty($CFG->maxcategorydepth
) && $depth >= $CFG->maxcategorydepth
) {
1762 if (!$displaylist) {
1763 make_categories_list($displaylist, $parentslist);
1767 if ($category->visible
or has_capability('moodle/category:viewhiddencategories', get_context_instance(CONTEXT_SYSTEM
))) {
1768 print_category_info($category, $depth, $showcourses);
1770 return; // Don't bother printing children of invisible categories
1774 $category->id
= "0";
1777 if ($categories = get_child_categories($category->id
)) { // Print all the children recursively
1778 $countcats = count($categories);
1782 foreach ($categories as $cat) {
1784 if ($count == $countcats) {
1787 $up = $first ?
false : true;
1788 $down = $last ?
false : true;
1791 print_whole_category_list($cat, $displaylist, $parentslist, $depth +
1, $showcourses);
1796 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1798 function make_categories_options() {
1799 make_categories_list($cats,$parents);
1800 foreach ($cats as $key => $value) {
1801 if (array_key_exists($key,$parents)) {
1802 if ($indent = count($parents[$key])) {
1803 for ($i = 0; $i < $indent; $i++
) {
1804 $cats[$key] = ' '.$cats[$key];
1812 function print_category_info($category, $depth, $showcourses = false) {
1813 /// Prints the category info in indented fashion
1814 /// This function is only used by print_whole_category_list() above
1817 static $strallowguests, $strrequireskey, $strsummary;
1819 if (empty($strsummary)) {
1820 $strallowguests = get_string('allowguests');
1821 $strrequireskey = get_string('requireskey');
1822 $strsummary = get_string('summary');
1825 $catlinkcss = $category->visible ?
'' : ' class="dimmed" ';
1827 static $coursecount = null;
1828 if (null === $coursecount) {
1829 // only need to check this once
1830 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT
;
1833 if ($showcourses and $coursecount) {
1834 $catimage = '<img src="'.$CFG->pixpath
.'/i/course.gif" alt="" />';
1836 $catimage = " ";
1839 echo "\n\n".'<table class="categorylist">';
1841 $courses = get_courses($category->id
, 'c.sortorder ASC', 'c.id,c.sortorder,c.visible,c.fullname,c.shortname,c.password,c.summary,c.guest,c.cost,c.currency');
1842 if ($showcourses and $coursecount) {
1847 $indent = $depth*30;
1848 $rows = count($courses) +
1;
1849 echo '<td class="category indentation" rowspan="'.$rows.'" valign="top">';
1850 print_spacer(10, $indent);
1854 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1855 echo '<td valign="top" class="category name">';
1856 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1858 echo '<td class="category info"> </td>';
1861 // does the depth exceed maxcategorydepth
1862 // maxcategorydepth == 0 or unset meant no limit
1864 $limit = !(isset($CFG->maxcategorydepth
) && ($depth >= $CFG->maxcategorydepth
-1));
1866 if ($courses && ($limit ||
$CFG->maxcategorydepth
== 0)) {
1867 foreach ($courses as $course) {
1868 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
1869 echo '<tr><td valign="top"> ';
1870 echo '</td><td valign="top" class="course name">';
1871 echo '<a '.$linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'. format_string($course->fullname
).'</a>';
1872 echo '</td><td align="right" valign="top" class="course info">';
1873 if ($course->guest
) {
1874 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1875 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath
.'/i/guest.gif" /></a>';
1877 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1879 if ($course->password
) {
1880 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">';
1881 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath
.'/i/key.gif" /></a>';
1883 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1885 if ($course->summary
) {
1886 link_to_popup_window ('/course/info.php?id='.$course->id
, 'courseinfo',
1887 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath
.'/i/info.gif" />',
1888 400, 500, $strsummary);
1890 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath
.'/spacer.gif" />';
1900 $indent = $depth*20;
1901 echo '<td class="category indentation" valign="top">';
1902 print_spacer(10, $indent);
1906 echo '<td valign="top" class="category name">';
1907 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot
.'/course/category.php?id='.$category->id
.'">'. format_string($category->name
).'</a>';
1909 echo '<td valign="top" class="category number">';
1910 if (count($courses)) {
1911 echo count($courses);
1919 * Print the buttons relating to course requests.
1921 * @param object $systemcontext the system context.
1923 function print_course_request_buttons($systemcontext) {
1925 if (empty($CFG->enablecourserequests
)) {
1928 if (isloggedin() && !isguestuser() && !has_capability('moodle/course:create', $systemcontext) && has_capability('moodle/course:request', $systemcontext)) {
1929 /// Print a button to request a new course
1930 print_single_button('request.php', NULL, get_string('requestcourse'), 'get');
1932 /// Print a button to manage pending requests
1933 if (has_capability('moodle/site:approvecourse', $systemcontext)) {
1934 print_single_button('pending.php', NULL, get_string('coursespending'), 'get', '_self', false, '', !record_exists('course_request'));
1939 * Prints the turn editing on/off button on course/index.php or course/category.php.
1941 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1942 * @return string HTML of the editing button, or empty string, if this user is not allowed
1945 function update_category_button($categoryid = 0) {
1948 // Check permissions.
1949 $context = get_category_or_system_context($categoryid);
1950 if (!has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context)) {
1954 // Work out the appropriate action.
1955 if (!empty($USER->categoryediting
)) {
1956 $label = get_string('turneditingoff');
1959 $label = get_string('turneditingon');
1963 // Generate the button HTML.
1964 $options = array('categoryedit' => $edit, 'sesskey' => sesskey());
1966 $options['id'] = $categoryid;
1967 $page = 'category.php';
1969 $page = 'index.php';
1971 return print_single_button($CFG->wwwroot
. '/course/' . $page, $options,
1972 $label, 'get', '', true);
1975 function print_courses($category) {
1976 /// Category is 0 (for all courses) or an object
1980 if (!is_object($category) && $category==0) {
1981 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1982 if (is_array($categories) && count($categories) == 1) {
1983 $category = array_shift($categories);
1984 $courses = get_courses_wmanagers($category->id
,
1986 array('password','summary','currency'));
1988 $courses = get_courses_wmanagers('all',
1990 array('password','summary','currency'));
1994 $courses = get_courses_wmanagers($category->id
,
1996 array('password','summary','currency'));
2000 echo '<ul class="unlist">';
2001 foreach ($courses as $course) {
2002 if ($course->visible
== 1
2003 ||
has_capability('moodle/course:viewhiddencourses',$course->context
)) {
2005 print_course($course);
2011 print_heading(get_string("nocoursesyet"));
2012 $context = get_context_instance(CONTEXT_SYSTEM
);
2013 if (has_capability('moodle/course:create', $context)) {
2015 $options['category'] = $category->id
;
2016 echo '<div class="addcoursebutton">';
2017 print_single_button($CFG->wwwroot
.'/course/edit.php', $options, get_string("addnewcourse"));
2024 * Print a description of a course, suitable for browsing in a list.
2026 * @param object $course the course object.
2027 * @param string $highlightterms (optional) some search terms that should be highlighted in the display.
2029 function print_course($course, $highlightterms = '') {
2033 if (isset($course->context
)) {
2034 $context = $course->context
;
2036 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2039 $linkcss = $course->visible ?
'' : ' class="dimmed" ';
2041 echo '<div class="coursebox clearfix">';
2042 echo '<div class="info">';
2043 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2044 $linkcss.' href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'.
2045 highlight($highlightterms, format_string($course->fullname
)).'</a></div>';
2047 /// first find all roles that are supposed to be displayed
2049 if (!empty($CFG->coursemanager
)) {
2050 $managerroles = split(',', $CFG->coursemanager
);
2051 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
2052 $namesarray = array();
2053 if (isset($course->managers
)) {
2054 if (count($course->managers
)) {
2055 $rusers = $course->managers
;
2056 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2058 /// Rename some of the role names if needed
2059 if (isset($context)) {
2060 $aliasnames = get_records('role_names', 'contextid', $context->id
,'','roleid,contextid,name');
2063 // keep a note of users displayed to eliminate duplicates
2064 $usersshown = array();
2065 foreach ($rusers as $ra) {
2067 // if we've already displayed user don't again
2068 if (in_array($ra->user
->id
,$usersshown)) {
2071 $usersshown[] = $ra->user
->id
;
2073 if ($ra->hidden
== 0 ||
$canseehidden) {
2074 $fullname = fullname($ra->user
, $canviewfullnames);
2075 if ($ra->hidden
== 1) {
2076 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
2081 if (isset($aliasnames[$ra->roleid
])) {
2082 $ra->rolename
= $aliasnames[$ra->roleid
]->name
;
2085 $namesarray[] = format_string($ra->rolename
)
2086 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$ra->user
->id
.'&course='.SITEID
.'">'
2087 . $fullname . '</a>' . $status;
2092 $rusers = get_role_users($managerroles, $context,
2093 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
2094 if (is_array($rusers) && count($rusers)) {
2095 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2097 /// Rename some of the role names if needed
2098 if (isset($context)) {
2099 $aliasnames = get_records('role_names', 'contextid', $context->id
,'','roleid,contextid,name');
2102 foreach ($rusers as $teacher) {
2103 $fullname = fullname($teacher, $canviewfullnames);
2105 /// Apply role names
2106 if (isset($aliasnames[$teacher->roleid
])) {
2107 $teacher->rolename
= $aliasnames[$teacher->roleid
]->name
;
2110 $namesarray[] = format_string($teacher->rolename
)
2111 . ': <a href="'.$CFG->wwwroot
.'/user/view.php?id='.$teacher->id
.'&course='.SITEID
.'">'
2112 . $fullname . '</a>';
2117 if (!empty($namesarray)) {
2118 echo "<ul class=\"teachers\">\n<li>";
2119 echo implode('</li><li>', $namesarray);
2124 require_once("$CFG->dirroot/enrol/enrol.class.php");
2125 $enrol = enrolment_factory
::factory($course->enrol
);
2126 echo $enrol->get_access_icons($course);
2128 echo '</div><div class="summary">';
2130 $options->noclean
= true;
2131 $options->para
= false;
2132 echo highlight($highlightterms, format_text($course->summary
, FORMAT_MOODLE
, $options, $course->id
));
2137 function print_my_moodle() {
2138 /// Prints custom user information on the home page.
2139 /// Over time this can include all sorts of information
2143 if (empty($USER->id
)) {
2144 error("It shouldn't be possible to see My Moodle without being logged in.");
2147 $courses = get_my_courses($USER->id
, 'visible DESC,sortorder ASC', array('summary'));
2149 $rcourses = array();
2150 if (!empty($CFG->mnet_dispatcher_mode
) && $CFG->mnet_dispatcher_mode
==='strict') {
2151 $rcourses = get_my_remotecourses($USER->id
);
2152 $rhosts = get_my_remotehosts();
2155 if (!empty($courses) ||
!empty($rcourses) ||
!empty($rhosts)) {
2157 if (!empty($courses)) {
2158 echo '<ul class="unlist">';
2159 foreach ($courses as $course) {
2160 if ($course->id
== SITEID
) {
2164 print_course($course);
2171 if (!empty($rcourses)) {
2172 // at the IDP, we know of all the remote courses
2173 foreach ($rcourses as $course) {
2174 print_remote_course($course, "100%");
2176 } elseif (!empty($rhosts)) {
2177 // non-IDP, we know of all the remote servers, but not courses
2178 foreach ($rhosts as $host) {
2179 print_remote_host($host, "100%");
2185 if (count_records("course") > (count($courses) +
1) ) { // Some courses not being displayed
2186 echo "<table width=\"100%\"><tr><td align=\"center\">";
2187 print_course_search("", false, "short");
2188 echo "</td><td align=\"center\">";
2189 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2190 echo "</td></tr></table>\n";
2194 if (count_records("course_categories") > 1) {
2195 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
2196 print_whole_category_list();
2197 print_simple_box_end();
2205 function print_course_search($value="", $return=false, $format="plain") {
2212 $id = 'coursesearch';
2218 $strsearchcourses= get_string("searchcourses");
2220 if ($format == 'plain') {
2221 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2222 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2223 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2224 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
2225 $output .= '<input type="submit" value="'.get_string('go').'" />';
2226 $output .= '</fieldset></form>';
2227 } else if ($format == 'short') {
2228 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2229 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2230 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2231 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2232 $output .= '<input type="submit" value="'.get_string('go').'" />';
2233 $output .= '</fieldset></form>';
2234 } else if ($format == 'navbar') {
2235 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot
.'/course/search.php" method="get">';
2236 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2237 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2238 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2239 $output .= '<input type="submit" value="'.get_string('go').'" />';
2240 $output .= '</fieldset></form>';
2249 function print_remote_course($course, $width="100%") {
2255 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&wantsurl=/course/view.php?id={$course->remoteid}";
2257 echo '<div class="coursebox remotecoursebox clearfix">';
2258 echo '<div class="info">';
2259 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2260 $linkcss.' href="'.$url.'">'
2261 . format_string($course->fullname
) .'</a><br />'
2262 . format_string($course->hostname
) . ' : '
2263 . format_string($course->cat_name
) . ' : '
2264 . format_string($course->shortname
). '</div>';
2265 echo '</div><div class="summary">';
2267 $options->noclean
= true;
2268 $options->para
= false;
2269 echo format_text($course->summary
, FORMAT_MOODLE
, $options);
2274 function print_remote_host($host, $width="100%") {
2280 echo '<div class="coursebox clearfix">';
2281 echo '<div class="info">';
2282 echo '<div class="name">';
2283 echo '<img src="'.$CFG->pixpath
.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2284 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2285 . s($host['name']).'</a> - ';
2286 echo $host['count'] . ' ' . get_string('courses');
2293 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2295 function add_course_module($mod) {
2297 $mod->added
= time();
2300 return insert_record("course_modules", $mod);
2304 * Returns course section - creates new if does not exist yet.
2305 * @param int $relative section number
2306 * @param int $courseid
2307 * @return object $course_section object
2309 function get_course_section($section, $courseid) {
2310 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2314 $cw->course
= $courseid;
2315 $cw->section
= $section;
2318 $id = insert_record("course_sections", $cw);
2319 return get_record("course_sections", "id", $id);
2322 * Given a full mod object with section and course already defined, adds this module to that section.
2324 * @param object $mod
2325 * @param int $beforemod An existing ID which we will insert the new module before
2326 * @return int The course_sections ID where the mod is inserted
2328 function add_mod_to_section($mod, $beforemod=NULL) {
2330 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2332 $section->sequence
= trim($section->sequence
);
2334 if (empty($section->sequence
)) {
2335 $newsequence = "$mod->coursemodule";
2337 } else if ($beforemod) {
2338 $modarray = explode(",", $section->sequence
);
2340 if ($key = array_keys ($modarray, $beforemod->id
)) {
2341 $insertarray = array($mod->id
, $beforemod->id
);
2342 array_splice($modarray, $key[0], 1, $insertarray);
2343 $newsequence = implode(",", $modarray);
2345 } else { // Just tack it on the end anyway
2346 $newsequence = "$section->sequence,$mod->coursemodule";
2350 $newsequence = "$section->sequence,$mod->coursemodule";
2353 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id
)) {
2354 return $section->id
; // Return course_sections ID that was used.
2359 } else { // Insert a new record
2360 $section->course
= $mod->course
;
2361 $section->section
= $mod->section
;
2362 $section->summary
= "";
2363 $section->sequence
= $mod->coursemodule
;
2364 return insert_record("course_sections", $section);
2368 function set_coursemodule_groupmode($id, $groupmode) {
2369 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2372 function set_coursemodule_groupingid($id, $groupingid) {
2373 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2376 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2377 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2380 function set_coursemodule_idnumber($id, $idnumber) {
2381 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2384 * $prevstateoverrides = true will set the visibility of the course module
2385 * to what is defined in visibleold. This enables us to remember the current
2386 * visibility when making a whole section hidden, so that when we toggle
2387 * that section back to visible, we are able to return the visibility of
2388 * the course module back to what it was originally.
2390 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2391 if (!$cm = get_record('course_modules', 'id', $id)) {
2394 if (!$modulename = get_field('modules', 'name', 'id', $cm->module
)) {
2397 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2398 foreach($events as $event) {
2406 if ($prevstateoverrides) {
2407 if ($visible == '0') {
2408 // Remember the current visible state so we can toggle this back.
2409 set_field('course_modules', 'visibleold', $cm->visible
, 'id', $id);
2411 // Get the previous saved visible states.
2412 return set_field('course_modules', 'visible', $cm->visibleold
, 'id', $id);
2415 return set_field("course_modules", "visible", $visible, "id", $id);
2419 * Delete a course module and any associated data at the course level (events)
2420 * Until 1.5 this function simply marked a deleted flag ... now it
2421 * deletes it completely.
2424 function delete_course_module($id) {
2426 require_once($CFG->libdir
.'/gradelib.php');
2428 if (!$cm = get_record('course_modules', 'id', $id)) {
2431 $modulename = get_field('modules', 'name', 'id', $cm->module
);
2432 //delete events from calendar
2433 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2434 foreach($events as $event) {
2435 delete_event($event->id
);
2438 //delete grade items, outcome items and grades attached to modules
2439 if ($grade_items = grade_item
::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2440 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
))) {
2441 foreach ($grade_items as $grade_item) {
2442 $grade_item->delete('moddelete');
2446 delete_context(CONTEXT_MODULE
, $cm->id
);
2447 return delete_records('course_modules', 'id', $cm->id
);
2450 function delete_mod_from_section($mod, $section) {
2452 if ($section = get_record("course_sections", "id", "$section") ) {
2454 $modarray = explode(",", $section->sequence
);
2456 if ($key = array_keys ($modarray, $mod)) {
2457 array_splice($modarray, $key[0], 1);
2458 $newsequence = implode(",", $modarray);
2459 return set_field("course_sections", "sequence", $newsequence, "id", $section->id
);
2469 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2471 * @param object $course
2472 * @param int $section
2473 * @param int $move (-1 or 1)
2475 function move_section($course, $section, $move) {
2476 /// Moves a whole course section up and down within the course
2483 $sectiondest = $section +
$move;
2485 if ($sectiondest > $course->numsections
or $sectiondest < 1) {
2489 if (!$sectionrecord = get_record("course_sections", "course", $course->id
, "section", $section)) {
2493 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id
, "section", $sectiondest)) {
2498 $count = abs($sectiondest - $section);
2499 $direction = ($sectiondest - $section) / $count;
2501 for ($i = 0, $ref = $section +
$direction; $i < $count; ++
$i, $ref +
= $direction) {
2502 if (!set_field("course_sections", "section", $ref - $direction, 'course', $course->id
, 'section', $ref)) {
2507 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id
)) {
2511 // if the focus is on the section that is being moved, then move the focus along
2512 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2513 course_set_display($course->id
, $sectiondest);
2516 // Check for duplicates and fix order if needed.
2517 // There is a very rare case that some sections in the same course have the same section id.
2518 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2520 foreach ($sections as $section) {
2521 if ($section->section
!= $n) {
2522 if (!set_field('course_sections', 'section', $n, 'id', $section->id
)) {
2532 * Moves a section within a course, from a position to another.
2533 * Be very careful: $section and $destination refer to section number,
2536 * @param object $course
2537 * @param int $section Section number (not id!!!)
2538 * @param int $destination
2539 * @return boolean Result
2541 function move_section_to($course, $section, $destination) {
2542 /// Moves a whole course section up and down within the course
2545 if (!$destination && $destination != 0) {
2549 if ($destination > $course->numsections
) {
2553 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2554 if (!$sections = get_records_menu('course_sections', 'course',$course->id
, 'section ASC, id ASC', 'id, section')) {
2558 $sections = reorder_sections($sections, $section, $destination);
2560 // Update all sections
2561 foreach ($sections as $id => $position) {
2562 set_field('course_sections', 'section', $position, 'id', $id);
2565 // if the focus is on the section that is being moved, then move the focus along
2566 if (isset($USER->display
[$course->id
]) and ($USER->display
[$course->id
] == $section)) {
2567 course_set_display($course->id
, $destination);
2573 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2574 * an original position number and a target position number, rebuilds the array so that the
2575 * move is made without any duplication of section positions.
2576 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2577 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2579 * @param array $sections
2580 * @param int $origin_position
2581 * @param int $target_position
2584 function reorder_sections($sections, $origin_position, $target_position) {
2585 if (!is_array($sections)) {
2589 // We can't move section position 0
2590 if ($origin_position < 1) {
2591 echo "We can't move section position 0";
2595 // Locate origin section in sections array
2596 if (!$origin_key = array_search($origin_position, $sections)) {
2597 echo "searched position not in sections array";
2598 return false; // searched position not in sections array
2601 // Extract origin section
2602 $origin_section = $sections[$origin_key];
2603 unset($sections[$origin_key]);
2605 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2607 $append_array = array();
2608 foreach ($sections as $id => $position) {
2610 $append_array[$id] = $position;
2611 unset($sections[$id]);
2613 if ($position == $target_position) {
2618 // Append moved section
2619 $sections[$origin_key] = $origin_section;
2621 // Append rest of array (if applicable)
2622 if (!empty($append_array)) {
2623 foreach ($append_array as $id => $position) {
2624 $sections[$id] = $position;
2628 // Renumber positions
2630 foreach ($sections as $id => $p) {
2631 $sections[$id] = $position;
2639 function moveto_module($mod, $section, $beforemod=NULL) {
2640 /// All parameters are objects
2641 /// Move the module object $mod to the specified $section
2642 /// If $beforemod exists then that is the module
2643 /// before which $modid should be inserted
2645 /// Remove original module from original section
2647 if (! delete_mod_from_section($mod->id
, $mod->section
)) {
2648 notify("Could not delete module from existing section");
2651 /// Update module itself if necessary
2653 if ($mod->section
!= $section->id
) {
2654 $mod->section
= $section->id
;
2655 if (!update_record("course_modules", $mod)) {
2658 // if moving to a hidden section then hide module
2659 if (!$section->visible
) {
2660 set_coursemodule_visible($mod->id
, 0);
2664 /// Add the module into the new section
2666 $mod->course
= $section->course
;
2667 $mod->section
= $section->section
; // need relative reference
2668 $mod->coursemodule
= $mod->id
;
2670 if (! add_mod_to_section($mod, $beforemod)) {
2678 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2684 $modcontext = get_context_instance(CONTEXT_MODULE
, $mod->id
);
2685 // no permission to edit
2686 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2691 $str->delete
= get_string("delete");
2692 $str->move
= get_string("move");
2693 $str->moveup
= get_string("moveup");
2694 $str->movedown
= get_string("movedown");
2695 $str->moveright
= get_string("moveright");
2696 $str->moveleft
= get_string("moveleft");
2697 $str->update
= get_string("update");
2698 $str->duplicate
= get_string("duplicate");
2699 $str->hide
= get_string("hide");
2700 $str->show
= get_string("show");
2701 $str->clicktochange
= get_string("clicktochange");
2702 $str->forcedmode
= get_string("forcedmode");
2703 $str->groupsnone
= get_string("groupsnone");
2704 $str->groupsseparate
= get_string("groupsseparate");
2705 $str->groupsvisible
= get_string("groupsvisible");
2706 $sesskey = sesskey();
2709 if ($section >= 0) {
2710 $section = '&sr='.$section; // Section return
2716 $path = $CFG->wwwroot
.'/course';
2721 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2722 if ($mod->visible
) {
2723 $hideshow = '<a class="editing_hide" title="'.$str->hide
.'" href="'.$path.'/mod.php?hide='.$mod->id
.
2724 '&sesskey='.$sesskey.$section.'"><img'.
2725 ' src="'.$CFG->pixpath
.'/t/hide.gif" class="iconsmall" '.
2726 ' alt="'.$str->hide
.'" /></a>'."\n";
2728 $hideshow = '<a class="editing_show" title="'.$str->show
.'" href="'.$path.'/mod.php?show='.$mod->id
.
2729 '&sesskey='.$sesskey.$section.'"><img'.
2730 ' src="'.$CFG->pixpath
.'/t/show.gif" class="iconsmall" '.
2731 ' alt="'.$str->show
.'" /></a>'."\n";
2737 if ($mod->groupmode
!== false) {
2738 if ($mod->groupmode
== SEPARATEGROUPS
) {
2739 $grouptitle = $str->groupsseparate
;
2740 $groupclass = 'editing_groupsseparate';
2741 $groupimage = $CFG->pixpath
.'/t/groups.gif';
2742 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=0&sesskey='.$sesskey;
2743 } else if ($mod->groupmode
== VISIBLEGROUPS
) {
2744 $grouptitle = $str->groupsvisible
;
2745 $groupclass = 'editing_groupsvisible';
2746 $groupimage = $CFG->pixpath
.'/t/groupv.gif';
2747 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=1&sesskey='.$sesskey;
2749 $grouptitle = $str->groupsnone
;
2750 $groupclass = 'editing_groupsnone';
2751 $groupimage = $CFG->pixpath
.'/t/groupn.gif';
2752 $grouplink = $path.'/mod.php?id='.$mod->id
.'&groupmode=2&sesskey='.$sesskey;
2754 if ($mod->groupmodelink
) {
2755 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange
.')" href="'.$grouplink.'">'.
2756 '<img src="'.$groupimage.'" class="iconsmall" '.
2757 'alt="'.$grouptitle.'" /></a>';
2759 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode
.')" '.
2760 ' src="'.$groupimage.'" class="iconsmall" '.
2761 'alt="'.$grouptitle.'" />';
2767 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2769 $move = '<a class="editing_move" title="'.$str->move
.'" href="'.$path.'/mod.php?copy='.$mod->id
.
2770 '&sesskey='.$sesskey.$section.'"><img'.
2771 ' src="'.$CFG->pixpath
.'/t/move.gif" class="iconsmall" '.
2772 ' alt="'.$str->move
.'" /></a>'."\n";
2774 $move = '<a class="editing_moveup" title="'.$str->moveup
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2775 '&move=-1&sesskey='.$sesskey.$section.'"><img'.
2776 ' src="'.$CFG->pixpath
.'/t/up.gif" class="iconsmall" '.
2777 ' alt="'.$str->moveup
.'" /></a>'."\n".
2778 '<a class="editing_movedown" title="'.$str->movedown
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2779 '&move=1&sesskey='.$sesskey.$section.'"><img'.
2780 ' src="'.$CFG->pixpath
.'/t/down.gif" class="iconsmall" '.
2781 ' alt="'.$str->movedown
.'" /></a>'."\n";
2788 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE
, $mod->course
))) {
2790 if (right_to_left()) { // Exchange arrows on RTL
2791 $rightarrow = 'left.gif';
2792 $leftarrow = 'right.gif';
2794 $rightarrow = 'right.gif';
2795 $leftarrow = 'left.gif';
2799 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2800 '&indent=-1&sesskey='.$sesskey.$section.'"><img'.
2801 ' src="'.$CFG->pixpath
.'/t/'.$leftarrow.'" class="iconsmall" '.
2802 ' alt="'.$str->moveleft
.'" /></a>'."\n";
2805 $leftright .= '<a class="editing_moveright" title="'.$str->moveright
.'" href="'.$path.'/mod.php?id='.$mod->id
.
2806 '&indent=1&sesskey='.$sesskey.$section.'"><img'.
2807 ' src="'.$CFG->pixpath
.'/t/'.$rightarrow.'" class="iconsmall" '.
2808 ' alt="'.$str->moveright
.'" /></a>'."\n";
2812 return '<span class="commands">'."\n".$leftright.$move.
2813 '<a class="editing_update" title="'.$str->update
.'" href="'.$path.'/mod.php?update='.$mod->id
.
2814 '&sesskey='.$sesskey.$section.'"><img'.
2815 ' src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" '.
2816 ' alt="'.$str->update
.'" /></a>'."\n".
2817 '<a class="editing_delete" title="'.$str->delete
.'" href="'.$path.'/mod.php?delete='.$mod->id
.
2818 '&sesskey='.$sesskey.$section.'"><img'.
2819 ' src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" '.
2820 ' alt="'.$str->delete
.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2824 * given a course object with shortname & fullname, this function will
2825 * truncate the the number of chars allowed and add ... if it was too long
2827 function course_format_name ($course,$max=100) {
2829 $str = $course->shortname
.': '. $course->fullname
;
2830 if (strlen($str) <= $max) {
2834 return substr($str,0,$max-3).'...';
2839 * This function will return true if the given course is a child course at all
2841 function course_in_meta ($course) {
2842 return record_exists("course_meta","child_course",$course->id
);
2847 * Print standard form elements on module setup forms in mod/.../mod.html
2849 function print_standard_coursemodule_settings($form, $features=null) {
2850 if (! $course = get_record('course', 'id', $form->course
)) {
2851 error("This course doesn't exist");
2853 print_groupmode_setting($form, $course);
2854 if (!empty($features->groupings
)) {
2855 print_grouping_settings($form, $course);
2857 print_visible_setting($form, $course);
2861 * Print groupmode form element on module setup forms in mod/.../mod.html
2863 function print_groupmode_setting($form, $course=NULL) {
2865 if (empty($course)) {
2866 if (! $course = get_record('course', 'id', $form->course
)) {
2867 error("This course doesn't exist");
2870 if ($form->coursemodule
) {
2871 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2872 error("This course module doesn't exist");
2874 $groupmode = groups_get_activity_groupmode($cm);
2877 $groupmode = groups_get_course_groupmode($course);
2879 if ($course->groupmode
or (!$course->groupmodeforce
)) {
2880 echo '<tr valign="top">';
2881 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2882 echo '<td align="left">';
2884 $choices[NOGROUPS
] = get_string('groupsnone');
2885 $choices[SEPARATEGROUPS
] = get_string('groupsseparate');
2886 $choices[VISIBLEGROUPS
] = get_string('groupsvisible');
2887 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce
);
2888 helpbutton('groupmode', get_string('groupmode'));
2894 * Print groupmode form element on module setup forms in mod/.../mod.html
2896 function print_grouping_settings($form, $course=NULL) {
2898 if (empty($course)) {
2899 if (! $course = get_record('course', 'id', $form->course
)) {
2900 error("This course doesn't exist");
2903 if ($form->coursemodule
) {
2904 if (! $cm = get_record('course_modules', 'id', $form->coursemodule
)) {
2905 error("This course module doesn't exist");
2911 $groupings = get_records_menu('groupings', 'courseid', $course->id
, 'name', 'id, name');
2912 if (!empty($groupings)) {
2913 echo '<tr valign="top">';
2914 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2915 echo '<td align="left">';
2918 $groupingid = isset($cm->groupingid
) ?
$cm->groupingid
: 0;
2920 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2923 $checked = empty($cm->groupmembersonly
) ?
'':'checked="checked"';
2924 echo '<tr valign="top">';
2925 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2926 echo '<td align="left">';
2927 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2934 * Print visibility setting form element on module setup forms in mod/.../mod.html
2936 function print_visible_setting($form, $course=NULL) {
2937 if (empty($course)) {
2938 if (! $course = get_record('course', 'id', $form->course
)) {
2939 error("This course doesn't exist");
2942 if ($form->coursemodule
) {
2943 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule
);
2948 if ($form->mode
== 'add') { // in this case $form->section is the section number, not the id
2949 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section
, 'course', $form->course
);
2951 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section
);
2953 if ($hiddensection) {
2957 echo '<tr valign="top">';
2958 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2959 echo '<td align="left">';
2960 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
2961 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2965 function update_restricted_mods($course,$mods) {
2967 /// Delete all the current restricted list
2968 delete_records('course_allowed_modules','course',$course->id
);
2970 if (empty($course->restrictmodules
)) {
2971 return; // We're done
2974 /// Insert the new list of restricted mods
2975 foreach ($mods as $mod) {
2977 continue; // this is the 'allow none' option
2980 $am->course
= $course->id
;
2982 insert_record('course_allowed_modules',$am);
2987 * This function will take an int (module id) or a string (module name)
2988 * and return true or false, whether it's allowed in the given course (object)
2989 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2990 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2993 function course_allowed_module($course,$mod) {
2995 if (empty($course->restrictmodules
)) {
2999 // Admins and admin-like people who can edit everything can also add anything.
3000 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
3001 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM
))) {
3005 if (is_numeric($mod)) {
3007 } else if (is_string($mod)) {
3008 $modid = get_field('modules','id','name',$mod);
3010 if (empty($modid)) {
3014 return (record_exists('course_allowed_modules','course',$course->id
,'module',$modid));
3018 * Recursively delete category including all subcategories and courses.
3019 * @param object $ccategory
3020 * @return bool status
3022 function category_delete_full($category, $showfeedback=true) {
3024 require_once($CFG->libdir
.'/gradelib.php');
3025 require_once($CFG->libdir
.'/questionlib.php');
3027 if ($children = get_records('course_categories', 'parent', $category->id
, 'sortorder ASC')) {
3028 foreach ($children as $childcat) {
3029 if (!category_delete_full($childcat, $showfeedback)) {
3030 notify("Error deleting category $childcat->name");
3036 if ($courses = get_records('course', 'category', $category->id
, 'sortorder ASC')) {
3037 foreach ($courses as $course) {
3038 if (!delete_course($course->id
, false)) {
3039 notify("Error deleting course $course->shortname");
3042 notify(get_string('coursedeleted', '', $course->shortname
), 'notifysuccess');
3046 // now delete anything that may depend on course category context
3047 grade_course_category_delete($category->id
, 0, $showfeedback);
3048 if (!question_delete_course_category($category, 0, $showfeedback)) {
3049 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3053 // finally delete the category and it's context
3054 delete_records('course_categories', 'id', $category->id
);
3055 delete_context(CONTEXT_COURSECAT
, $category->id
);
3057 events_trigger('course_category_deleted', $category);
3059 notify(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3065 * Delete category, but move contents to another category.
3066 * @param object $ccategory
3067 * @param int $newparentid category id
3068 * @return bool status
3070 function category_delete_move($category, $newparentid, $showfeedback=true) {
3072 require_once($CFG->libdir
.'/gradelib.php');
3073 require_once($CFG->libdir
.'/questionlib.php');
3075 if (!$newparentcat = get_record('course_categories', 'id', $newparentid)) {
3079 if ($children = get_records('course_categories', 'parent', $category->id
, 'sortorder ASC')) {
3080 foreach ($children as $childcat) {
3081 if (!move_category($childcat, $newparentcat)) {
3082 notify("Error moving category $childcat->name");
3088 if ($courses = get_records('course', 'category', $category->id
, 'sortorder ASC', 'id')) {
3089 if (!move_courses(array_keys($courses), $newparentid)) {
3090 notify("Error moving courses");
3093 notify(get_string('coursesmovedout', '', format_string($category->name
)), 'notifysuccess');
3096 // now delete anything that may depend on course category context
3097 grade_course_category_delete($category->id
, $newparentid, $showfeedback);
3098 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
3099 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
3103 // finally delete the category and it's context
3104 delete_records('course_categories', 'id', $category->id
);
3105 delete_context(CONTEXT_COURSECAT
, $category->id
);
3107 events_trigger('course_category_deleted', $category);
3109 notify(get_string('coursecategorydeleted', '', format_string($category->name
)), 'notifysuccess');
3115 *** Efficiently moves many courses around while maintaining
3116 *** sortorder in order.
3118 *** $courseids is an array of course ids
3122 function move_courses ($courseids, $categoryid) {
3126 if (!empty($courseids)) {
3128 $courseids = array_reverse($courseids);
3130 foreach ($courseids as $courseid) {
3132 if (! $course = get_record("course", "id", $courseid)) {
3133 notify("Error finding course $courseid");
3135 // figure out a sortorder that we can use in the destination category
3136 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
3137 FROM ' . $CFG->prefix
. 'course WHERE category=' . $categoryid);
3138 if (is_null($sortorder) ||
$sortorder === false) {
3139 // the category is empty
3140 // rather than let the db default to 0
3141 // set it to > 100 and avoid extra work in fix_coursesortorder()
3143 } else if ($sortorder < 10) {
3144 fix_course_sortorder($categoryid);
3147 $course->category
= $categoryid;
3148 $course->sortorder
= $sortorder;
3150 if (!update_record('course', addslashes_recursive($course))) {
3151 notify("An error occurred - course not moved!");
3154 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3155 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3156 context_moved($context, $newparent);
3159 fix_course_sortorder();
3165 *** Efficiently moves a category - NOTE that this can have
3166 *** a huge impact access-control-wise...
3170 function move_category ($category, $newparentcat) {
3174 $context = get_context_instance(CONTEXT_COURSECAT
, $category->id
);
3176 if (empty($newparentcat->id
)) {
3177 if (!set_field('course_categories', 'parent', 0, 'id', $category->id
)) {
3180 $newparent = get_context_instance(CONTEXT_SYSTEM
);
3182 if (!set_field('course_categories', 'parent', $newparentcat->id
, 'id', $category->id
)) {
3185 $newparent = get_context_instance(CONTEXT_COURSECAT
, $newparentcat->id
);
3188 context_moved($context, $newparent);
3190 // The most effective thing would be to find the common parent,
3191 // until then, do it sitewide...
3192 fix_course_sortorder();
3199 * @param string $format Course format ID e.g. 'weeks'
3200 * @return Name that the course format prefers for sections
3202 function get_section_name($format) {
3203 $sectionname = get_string("name$format","format_$format");
3204 if($sectionname == "[[name$format]]") {
3205 $sectionname = get_string("name$format");
3207 return $sectionname;
3211 * Can the current user delete this course?
3212 * Course creators have exception,
3213 * 1 day after the creation they can sill delete the course.
3214 * @param int $courseid
3217 function can_delete_course($courseid) {
3220 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3222 if (has_capability('moodle/course:delete', $context)) {
3226 // hack: now try to find out if creator created this course recently (1 day)
3227 if (!has_capability('moodle/course:create', $context)) {
3231 $since = time() - 60*60*24;
3233 $select = "module = 'course' AND action = 'new' AND userid = $USER->id AND url='view.php?id=$courseid' AND time > $since";
3235 return record_exists_select('log', $select);
3239 * Save the Your name for 'Some role' strings.
3241 * @param integer $courseid the id of this course.
3242 * @param array $data the data that came from the course settings form.
3244 function save_local_role_names($courseid, $data) {
3245 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3247 foreach ($data as $fieldname => $value) {
3248 if (!strstr($fieldname, 'role_')) {
3251 list($ignored, $roleid) = explode('_', $fieldname);
3253 // make up our mind whether we want to delete, update or insert
3255 delete_records('role_names', 'contextid', $context->id
, 'roleid', $roleid);
3257 } else if ($rolename = get_record('role_names', 'contextid', $context->id
, 'roleid', $roleid)) {
3258 $rolename->name
= $value;
3259 update_record('role_names', $rolename);
3262 $rolename = new stdClass
;
3263 $rolename->contextid
= $context->id
;
3264 $rolename->roleid
= $roleid;
3265 $rolename->name
= $value;
3266 insert_record('role_names', $rolename, false);
3272 * Create a course and either return a $course object or false
3274 * @param object $data - all the data needed for an entry in the 'course' table
3276 function create_course($data) {
3279 // preprocess allowed mods
3280 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
3281 unset($data->allowedmods
);
3282 if ($CFG->restrictmodulesfor
== 'all') {
3283 $data->restrictmodules
= 1;
3285 // if the user is not an admin, get the default allowed modules because
3286 // there are no modules passed by the form
3287 if(!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3288 if(!$allowedmods && $CFG->defaultallowedmodules
) {
3289 $allowedmods = explode(',', $CFG->defaultallowedmodules
);
3293 $data->restrictmodules
= 0;
3296 $data->timecreated
= time();
3298 // place at beginning of category
3299 fix_course_sortorder();
3300 $data->sortorder
= get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
3301 if (empty($data->sortorder
)) {
3302 $data->sortorder
= 100;
3305 if ($newcourseid = insert_record('course', $data)) { // Set up new course
3307 $course = get_record('course', 'id', $newcourseid);
3310 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
3311 blocks_repopulate_page($page); // Return value not checked because you can always edit later
3313 update_restricted_mods($course, $allowedmods);
3315 $section = new object();
3316 $section->course
= $course->id
; // Create a default section.
3317 $section->section
= 0;
3318 $section->id
= insert_record('course_sections', $section);
3320 fix_course_sortorder();
3322 add_to_log(SITEID
, 'course', 'new', 'view.php?id='.$course->id
, $data->fullname
.' (ID '.$course->id
.')');
3324 // Save any custom role names.
3325 save_local_role_names($course->id
, $data);
3328 events_trigger('course_created', $course);
3333 return false; // error
3337 * Update a course and return true or false
3339 * @param object $data - all the data needed for an entry in the 'course' table
3341 function update_course($data) {
3344 // Preprocess allowed mods
3345 $allowedmods = empty($data->allowedmods
) ?
array() : $data->allowedmods
;
3346 unset($data->allowedmods
);
3348 // Normal teachers can't change setting
3349 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3350 unset($data->restrictmodules
);
3354 $oldcourse = get_record('course', 'id', $data->id
); // should not fail, already tested above
3355 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $oldcourse->category
))
3356 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $data->category
))) {
3357 // can not move to new category, keep the old one
3358 unset($data->category
);
3359 } elseif ($oldcourse->category
!= $data->category
) {
3363 // Update with the new data
3364 if (update_record('course', $data)) {
3366 $course = get_record('course', 'id', $data->id
);
3368 add_to_log($course->id
, "course", "update", "edit.php?id=$course->id", $course->id
);
3370 // "Admins" can change allowed mods for a course
3371 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
))) {
3372 update_restricted_mods($course, $allowedmods);
3376 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
3377 $newparent = get_context_instance(CONTEXT_COURSECAT
, $course->category
);
3378 context_moved($context, $newparent);
3381 fix_course_sortorder();
3383 // Test for and remove blocks which aren't appropriate anymore
3384 $page = page_create_object(PAGE_COURSE_VIEW
, $course->id
);
3385 blocks_remove_inappropriate($page);
3387 // Save any custom role names.
3388 save_local_role_names($course->id
, $data);
3391 events_trigger('course_updated', $course);