Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / course / lib.php
blob2dcbee7207206bddfdea9742f4a041937b7bedb1
1 <?php // $Id$
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 define('FRONTPAGECOURSELIMIT', 200); // maximum number of courses displayed on the frontpage
18 define('EXCELROWS', 65535);
19 define('FIRSTUSEDEXCELROW', 3);
21 define('MOD_CLASS_ACTIVITY', 0);
22 define('MOD_CLASS_RESOURCE', 1);
25 function make_log_url($module, $url) {
26 switch ($module) {
27 case 'course':
28 case 'file':
29 case 'login':
30 case 'lib':
31 case 'admin':
32 case 'calendar':
33 case 'mnet course':
34 return "/course/$url";
35 break;
36 case 'user':
37 case 'blog':
38 return "/$module/$url";
39 break;
40 case 'upload':
41 return $url;
42 break;
43 case 'library':
44 case '':
45 return '/';
46 break;
47 case 'message':
48 return "/message/$url";
49 break;
50 default:
51 return "/mod/$module/$url";
52 break;
57 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
58 $modname="", $modid=0, $modaction="", $groupid=0) {
60 global $CFG;
62 // It is assumed that $date is the GMT time of midnight for that day,
63 // and so the next 86400 seconds worth of logs are printed.
65 /// Setup for group handling.
67 // TODO: I don't understand group/context/etc. enough to be able to do
68 // something interesting with it here
69 // What is the context of a remote course?
71 /// If the group mode is separate, and this user does not have editing privileges,
72 /// then only the user's group can be viewed.
73 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
74 // $groupid = get_current_group($course->id);
75 //}
76 /// If this course doesn't have groups, no groupid can be specified.
77 //else if (!$course->groupmode) {
78 // $groupid = 0;
79 //}
80 $groupid = 0;
82 $joins = array();
84 $qry = "
85 SELECT
86 l.*,
87 u.firstname,
88 u.lastname,
89 u.picture
90 FROM
91 {$CFG->prefix}mnet_log l
92 LEFT JOIN
93 {$CFG->prefix}user u
95 l.userid = u.id
96 WHERE
99 $where .= "l.hostid = '$hostid'";
101 // TODO: Is 1 really a magic number referring to the sitename?
102 if ($course != 1 || $modid != 0) {
103 $where .= " AND\n l.course='$course'";
106 if ($modname) {
107 $where .= " AND\n l.module = '$modname'";
110 if ('site_errors' === $modid) {
111 $where .= " AND\n ( l.action='error' OR l.action='infected' )";
112 } else if ($modid) {
113 //TODO: This assumes that modids are the same across sites... probably
114 //not true
115 $where .= " AND\n l.cmid = '$modid'";
118 if ($modaction) {
119 $firstletter = substr($modaction, 0, 1);
120 if (preg_match('/[[:alpha:]]/', $firstletter)) {
121 $where .= " AND\n lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
122 } else if ($firstletter == '-') {
123 $where .= " AND\n lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
127 if ($user) {
128 $where .= " AND\n l.userid = '$user'";
131 if ($date) {
132 $enddate = $date + 86400;
133 $where .= " AND\n l.time > '$date' AND l.time < '$enddate'";
136 $result = array();
137 $result['totalcount'] = count_records_sql("SELECT COUNT(*) FROM {$CFG->prefix}mnet_log l WHERE $where");
138 if(!empty($result['totalcount'])) {
139 $where .= "\n ORDER BY\n $order";
140 $result['logs'] = get_records_sql($qry.$where, $limitfrom, $limitnum);
141 } else {
142 $result['logs'] = array();
144 return $result;
147 function build_logs_array($course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
148 $modname="", $modid=0, $modaction="", $groupid=0) {
150 // It is assumed that $date is the GMT time of midnight for that day,
151 // and so the next 86400 seconds worth of logs are printed.
153 /// Setup for group handling.
155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
157 if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
158 $groupid = get_current_group($course->id);
160 /// If this course doesn't have groups, no groupid can be specified.
161 else if (!$course->groupmode) {
162 $groupid = 0;
165 $joins = array();
167 if ($course->id != SITEID || $modid != 0) {
168 $joins[] = "l.course='$course->id'";
171 if ($modname) {
172 $joins[] = "l.module = '$modname'";
175 if ('site_errors' === $modid) {
176 $joins[] = "( l.action='error' OR l.action='infected' )";
177 } else if ($modid) {
178 $joins[] = "l.cmid = '$modid'";
181 if ($modaction) {
182 $firstletter = substr($modaction, 0, 1);
183 if (preg_match('/[[:alpha:]]/', $firstletter)) {
184 $joins[] = "lower(l.action) LIKE '%" . strtolower($modaction) . "%'";
185 } else if ($firstletter == '-') {
186 $joins[] = "lower(l.action) NOT LIKE '%" . strtolower(substr($modaction, 1)) . "%'";
191 /// Getting all members of a group.
192 if ($groupid and !$user) {
193 if ($gusers = groups_get_members($groupid)) {
194 $gusers = array_keys($gusers);
195 $joins[] = 'l.userid IN (' . implode(',', $gusers) . ')';
196 } else {
197 $joins[] = 'l.userid = 0'; // No users in groups, so we want something that will always be false.
200 else if ($user) {
201 $joins[] = "l.userid = '$user'";
204 if ($date) {
205 $enddate = $date + 86400;
206 $joins[] = "l.time > '$date' AND l.time < '$enddate'";
209 $selector = implode(' AND ', $joins);
211 $totalcount = 0; // Initialise
212 $result = array();
213 $result['logs'] = get_logs($selector, $order, $limitfrom, $limitnum, $totalcount);
214 $result['totalcount'] = $totalcount;
215 return $result;
219 function print_log($course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
220 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
222 global $CFG;
224 if (!$logs = build_logs_array($course, $user, $date, $order, $page*$perpage, $perpage,
225 $modname, $modid, $modaction, $groupid)) {
226 notify("No logs found!");
227 print_footer($course);
228 exit;
231 $courses = array();
233 if ($course->id == SITEID) {
234 $courses[0] = '';
235 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
236 foreach ($ccc as $cc) {
237 $courses[$cc->id] = $cc->shortname;
240 } else {
241 $courses[$course->id] = $course->shortname;
244 $totalcount = $logs['totalcount'];
245 $count=0;
246 $ldcache = array();
247 $tt = getdate(time());
248 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
250 $strftimedatetime = get_string("strftimedatetime");
252 echo "<div class=\"info\">\n";
253 print_string("displayingrecords", "", $totalcount);
254 echo "</div>\n";
256 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
258 echo '<table class="logtable genearlbox boxaligncenter" summary="">'."\n";
259 // echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\" summary=\"\">\n";
260 echo "<tr>";
261 if ($course->id == SITEID) {
262 echo "<th class=\"c0 header\" scope=\"col\">".get_string('course')."</th>\n";
264 echo "<th class=\"c1 header\" scope=\"col\">".get_string('time')."</th>\n";
265 echo "<th class=\"c2 header\" scope=\"col\">".get_string('ip_address')."</th>\n";
266 echo "<th class=\"c3 header\" scope=\"col\">".get_string('fullname')."</th>\n";
267 echo "<th class=\"c4 header\" scope=\"col\">".get_string('action')."</th>\n";
268 echo "<th class=\"c5 header\" scope=\"col\">".get_string('info')."</th>\n";
269 echo "</tr>\n";
271 // Make sure that the logs array is an array, even it is empty, to avoid warnings from the foreach.
272 if (empty($logs['logs'])) {
273 $logs['logs'] = array();
276 $row = 1;
277 foreach ($logs['logs'] as $log) {
279 $row = ($row + 1) % 2;
281 if (isset($ldcache[$log->module][$log->action])) {
282 $ld = $ldcache[$log->module][$log->action];
283 } else {
284 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
285 $ldcache[$log->module][$log->action] = $ld;
287 if ($ld && is_numeric($log->info)) {
288 // ugly hack to make sure fullname is shown correctly
289 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
290 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
291 } else {
292 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
296 //Filter log->info
297 $log->info = format_string($log->info);
299 // If $log->url has been trimmed short by the db size restriction
300 // code in add_to_log, keep a note so we don't add a link to a broken url
301 $tl=textlib_get_instance();
302 $brokenurl=($tl->strlen($log->url)==100 && $tl->substr($log->url,97)=='...');
304 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
305 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
306 $log->url = s($log->url); /// XSS protection and XHTML compatibility - should be in link_to_popup_window() instead!!
308 echo '<tr class="r'.$row.'">';
309 if ($course->id == SITEID) {
310 echo "<td class=\"cell c0\">\n";
311 if (empty($log->course)) {
312 echo get_string('site') . "\n";
313 } else {
314 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">". format_string($courses[$log->course])."</a>\n";
316 echo "</td>\n";
318 echo "<td class=\"cell c1\" align=\"right\">".userdate($log->time, '%a').
319 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
320 echo "<td class=\"cell c2\">\n";
321 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 440, 700);
322 echo "</td>\n";
323 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
324 echo "<td class=\"cell c3\">\n";
325 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}&amp;course={$log->course}\">$fullname</a>\n";
326 echo "</td>\n";
327 echo "<td class=\"cell c4\">\n";
328 $displayaction="$log->module $log->action";
329 if($brokenurl) {
330 echo $displayaction;
331 } else {
332 link_to_popup_window( make_log_url($log->module,$log->url), 'fromloglive',$displayaction, 440, 700);
334 echo "</td>\n";;
335 echo "<td class=\"cell c5\">{$log->info}</td>\n";
336 echo "</tr>\n";
338 echo "</table>\n";
340 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
344 function print_mnet_log($hostid, $course, $user=0, $date=0, $order="l.time ASC", $page=0, $perpage=100,
345 $url="", $modname="", $modid=0, $modaction="", $groupid=0) {
347 global $CFG;
349 if (!$logs = build_mnet_logs_array($hostid, $course, $user, $date, $order, $page*$perpage, $perpage,
350 $modname, $modid, $modaction, $groupid)) {
351 notify("No logs found!");
352 print_footer($course);
353 exit;
356 if ($course->id == SITEID) {
357 $courses[0] = '';
358 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname,c.visible')) {
359 foreach ($ccc as $cc) {
360 $courses[$cc->id] = $cc->shortname;
365 $totalcount = $logs['totalcount'];
366 $count=0;
367 $ldcache = array();
368 $tt = getdate(time());
369 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
371 $strftimedatetime = get_string("strftimedatetime");
373 echo "<div class=\"info\">\n";
374 print_string("displayingrecords", "", $totalcount);
375 echo "</div>\n";
377 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
379 echo "<table class=\"logtable\" cellpadding=\"3\" cellspacing=\"0\">\n";
380 echo "<tr>";
381 if ($course->id == SITEID) {
382 echo "<th class=\"c0 header\">".get_string('course')."</th>\n";
384 echo "<th class=\"c1 header\">".get_string('time')."</th>\n";
385 echo "<th class=\"c2 header\">".get_string('ip_address')."</th>\n";
386 echo "<th class=\"c3 header\">".get_string('fullname')."</th>\n";
387 echo "<th class=\"c4 header\">".get_string('action')."</th>\n";
388 echo "<th class=\"c5 header\">".get_string('info')."</th>\n";
389 echo "</tr>\n";
391 if (empty($logs['logs'])) {
392 echo "</table>\n";
393 return;
396 $row = 1;
397 foreach ($logs['logs'] as $log) {
399 $log->info = $log->coursename;
400 $row = ($row + 1) % 2;
402 if (isset($ldcache[$log->module][$log->action])) {
403 $ld = $ldcache[$log->module][$log->action];
404 } else {
405 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
406 $ldcache[$log->module][$log->action] = $ld;
408 if (0 && $ld && !empty($log->info)) {
409 // ugly hack to make sure fullname is shown correctly
410 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
411 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
412 } else {
413 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
417 //Filter log->info
418 $log->info = format_string($log->info);
420 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
421 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
422 $log->url = str_replace('&', '&amp;', $log->url); /// XHTML compatibility
424 echo '<tr class="r'.$row.'">';
425 if ($course->id == SITEID) {
426 echo "<td class=\"r$row c0\" >\n";
427 echo " <a href=\"{$CFG->wwwroot}/course/view.php?id={$log->course}\">".$courses[$log->course]."</a>\n";
428 echo "</td>\n";
430 echo "<td class=\"r$row c1\" align=\"right\">".userdate($log->time, '%a').
431 ' '.userdate($log->time, $strftimedatetime)."</td>\n";
432 echo "<td class=\"r$row c2\" >\n";
433 link_to_popup_window("/iplookup/index.php?ip=$log->ip&amp;user=$log->userid", 'iplookup',$log->ip, 400, 700);
434 echo "</td>\n";
435 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
436 echo "<td class=\"r$row c3\" >\n";
437 echo " <a href=\"$CFG->wwwroot/user/view.php?id={$log->userid}\">$fullname</a>\n";
438 echo "</td>\n";
439 echo "<td class=\"r$row c4\">\n";
440 echo $log->action .': '.$log->module;
441 echo "</td>\n";;
442 echo "<td class=\"r$row c5\">{$log->info}</td>\n";
443 echo "</tr>\n";
445 echo "</table>\n";
447 print_paging_bar($totalcount, $page, $perpage, "$url&amp;perpage=$perpage&amp;");
451 function print_log_csv($course, $user, $date, $order='l.time DESC', $modname,
452 $modid, $modaction, $groupid) {
454 $text = get_string('course')."\t".get_string('time')."\t".get_string('ip_address')."\t".
455 get_string('fullname')."\t".get_string('action')."\t".get_string('info');
457 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
458 $modname, $modid, $modaction, $groupid)) {
459 return false;
462 $courses = array();
464 if ($course->id == SITEID) {
465 $courses[0] = '';
466 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
467 foreach ($ccc as $cc) {
468 $courses[$cc->id] = $cc->shortname;
471 } else {
472 $courses[$course->id] = $course->shortname;
475 $count=0;
476 $ldcache = array();
477 $tt = getdate(time());
478 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
480 $strftimedatetime = get_string("strftimedatetime");
482 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
483 $filename .= '.txt';
484 header("Content-Type: application/download\n");
485 header("Content-Disposition: attachment; filename=$filename");
486 header("Expires: 0");
487 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
488 header("Pragma: public");
490 echo get_string('savedat').userdate(time(), $strftimedatetime)."\n";
491 echo $text;
493 if (empty($logs['logs'])) {
494 return true;
497 foreach ($logs['logs'] as $log) {
498 if (isset($ldcache[$log->module][$log->action])) {
499 $ld = $ldcache[$log->module][$log->action];
500 } else {
501 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
502 $ldcache[$log->module][$log->action] = $ld;
504 if ($ld && !empty($log->info)) {
505 // ugly hack to make sure fullname is shown correctly
506 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
507 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
508 } else {
509 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
513 //Filter log->info
514 $log->info = format_string($log->info);
516 $log->url = strip_tags(urldecode($log->url)); // Some XSS protection
517 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
518 $log->url = str_replace('&', '&amp;', $log->url); // XHTML compatibility
520 $firstField = $courses[$log->course];
521 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
522 $row = array($firstField, userdate($log->time, $strftimedatetime), $log->ip, $fullname, $log->module.' '.$log->action, $log->info);
523 $text = implode("\t", $row);
524 echo $text." \n";
526 return true;
530 function print_log_xls($course, $user, $date, $order='l.time DESC', $modname,
531 $modid, $modaction, $groupid) {
533 global $CFG;
535 require_once("$CFG->libdir/excellib.class.php");
537 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
538 $modname, $modid, $modaction, $groupid)) {
539 return false;
542 $courses = array();
544 if ($course->id == SITEID) {
545 $courses[0] = '';
546 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
547 foreach ($ccc as $cc) {
548 $courses[$cc->id] = $cc->shortname;
551 } else {
552 $courses[$course->id] = $course->shortname;
555 $count=0;
556 $ldcache = array();
557 $tt = getdate(time());
558 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
560 $strftimedatetime = get_string("strftimedatetime");
562 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
563 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
564 $filename .= '.xls';
566 $workbook = new MoodleExcelWorkbook('-');
567 $workbook->send($filename);
569 $worksheet = array();
570 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
571 get_string('fullname'), get_string('action'), get_string('info'));
573 // Creating worksheets
574 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
575 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
576 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
577 $worksheet[$wsnumber]->set_column(1, 1, 30);
578 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
579 userdate(time(), $strftimedatetime));
580 $col = 0;
581 foreach ($headers as $item) {
582 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
583 $col++;
587 if (empty($logs['logs'])) {
588 $workbook->close();
589 return true;
592 $formatDate =& $workbook->add_format();
593 $formatDate->set_num_format(get_string('log_excel_date_format'));
595 $row = FIRSTUSEDEXCELROW;
596 $wsnumber = 1;
597 $myxls =& $worksheet[$wsnumber];
598 foreach ($logs['logs'] as $log) {
599 if (isset($ldcache[$log->module][$log->action])) {
600 $ld = $ldcache[$log->module][$log->action];
601 } else {
602 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
603 $ldcache[$log->module][$log->action] = $ld;
605 if ($ld && !empty($log->info)) {
606 // ugly hack to make sure fullname is shown correctly
607 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
608 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
609 } else {
610 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
614 // Filter log->info
615 $log->info = format_string($log->info);
616 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
618 if ($nroPages>1) {
619 if ($row > EXCELROWS) {
620 $wsnumber++;
621 $myxls =& $worksheet[$wsnumber];
622 $row = FIRSTUSEDEXCELROW;
626 $myxls->write($row, 0, $courses[$log->course], '');
627 // Excel counts from 1/1/1900
628 $excelTime=25569+$log->time/(3600*24);
629 $myxls->write($row, 1, $excelTime, $formatDate);
630 $myxls->write($row, 2, $log->ip, '');
631 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
632 $myxls->write($row, 3, $fullname, '');
633 $myxls->write($row, 4, $log->module.' '.$log->action, '');
634 $myxls->write($row, 5, $log->info, '');
636 $row++;
639 $workbook->close();
640 return true;
643 function print_log_ods($course, $user, $date, $order='l.time DESC', $modname,
644 $modid, $modaction, $groupid) {
646 global $CFG;
648 require_once("$CFG->libdir/odslib.class.php");
650 if (!$logs = build_logs_array($course, $user, $date, $order, '', '',
651 $modname, $modid, $modaction, $groupid)) {
652 return false;
655 $courses = array();
657 if ($course->id == SITEID) {
658 $courses[0] = '';
659 if ($ccc = get_courses('all', 'c.id ASC', 'c.id,c.shortname')) {
660 foreach ($ccc as $cc) {
661 $courses[$cc->id] = $cc->shortname;
664 } else {
665 $courses[$course->id] = $course->shortname;
668 $count=0;
669 $ldcache = array();
670 $tt = getdate(time());
671 $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
673 $strftimedatetime = get_string("strftimedatetime");
675 $nroPages = ceil(count($logs)/(EXCELROWS-FIRSTUSEDEXCELROW+1));
676 $filename = 'logs_'.userdate(time(),get_string('backupnameformat'),99,false);
677 $filename .= '.ods';
679 $workbook = new MoodleODSWorkbook('-');
680 $workbook->send($filename);
682 $worksheet = array();
683 $headers = array(get_string('course'), get_string('time'), get_string('ip_address'),
684 get_string('fullname'), get_string('action'), get_string('info'));
686 // Creating worksheets
687 for ($wsnumber = 1; $wsnumber <= $nroPages; $wsnumber++) {
688 $sheettitle = get_string('logs').' '.$wsnumber.'-'.$nroPages;
689 $worksheet[$wsnumber] =& $workbook->add_worksheet($sheettitle);
690 $worksheet[$wsnumber]->set_column(1, 1, 30);
691 $worksheet[$wsnumber]->write_string(0, 0, get_string('savedat').
692 userdate(time(), $strftimedatetime));
693 $col = 0;
694 foreach ($headers as $item) {
695 $worksheet[$wsnumber]->write(FIRSTUSEDEXCELROW-1,$col,$item,'');
696 $col++;
700 if (empty($logs['logs'])) {
701 $workbook->close();
702 return true;
705 $formatDate =& $workbook->add_format();
706 $formatDate->set_num_format(get_string('log_excel_date_format'));
708 $row = FIRSTUSEDEXCELROW;
709 $wsnumber = 1;
710 $myxls =& $worksheet[$wsnumber];
711 foreach ($logs['logs'] as $log) {
712 if (isset($ldcache[$log->module][$log->action])) {
713 $ld = $ldcache[$log->module][$log->action];
714 } else {
715 $ld = get_record('log_display', 'module', $log->module, 'action', $log->action);
716 $ldcache[$log->module][$log->action] = $ld;
718 if ($ld && !empty($log->info)) {
719 // ugly hack to make sure fullname is shown correctly
720 if (($ld->mtable == 'user') and ($ld->field == sql_concat('firstname', "' '" , 'lastname'))) {
721 $log->info = fullname(get_record($ld->mtable, 'id', $log->info), true);
722 } else {
723 $log->info = get_field($ld->mtable, $ld->field, 'id', $log->info);
727 // Filter log->info
728 $log->info = format_string($log->info);
729 $log->info = strip_tags(urldecode($log->info)); // Some XSS protection
731 if ($nroPages>1) {
732 if ($row > EXCELROWS) {
733 $wsnumber++;
734 $myxls =& $worksheet[$wsnumber];
735 $row = FIRSTUSEDEXCELROW;
739 $myxls->write_string($row, 0, $courses[$log->course]);
740 $myxls->write_date($row, 1, $log->time);
741 $myxls->write_string($row, 2, $log->ip);
742 $fullname = fullname($log, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
743 $myxls->write_string($row, 3, $fullname);
744 $myxls->write_string($row, 4, $log->module.' '.$log->action);
745 $myxls->write_string($row, 5, $log->info);
747 $row++;
750 $workbook->close();
751 return true;
755 function print_log_graph($course, $userid=0, $type="course.png", $date=0) {
756 global $CFG, $USER;
757 if (empty($CFG->gdversion)) {
758 echo "(".get_string("gdneed").")";
759 } else {
760 // MDL-10818, do not display broken graph when user has no permission to view graph
761 if (has_capability('moodle/site:viewreports', get_context_instance(CONTEXT_COURSE, $course->id)) ||
762 ($course->showreports and $USER->id == $userid)) {
763 echo '<img src="'.$CFG->wwwroot.'/course/report/log/graph.php?id='.$course->id.
764 '&amp;user='.$userid.'&amp;type='.$type.'&amp;date='.$date.'" alt="" />';
770 function print_overview($courses) {
772 global $CFG, $USER;
774 $htmlarray = array();
775 if ($modules = get_records('modules')) {
776 foreach ($modules as $mod) {
777 if (file_exists(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php')) {
778 include_once(dirname(dirname(__FILE__)).'/mod/'.$mod->name.'/lib.php');
779 $fname = $mod->name.'_print_overview';
780 if (function_exists($fname)) {
781 $fname($courses,$htmlarray);
786 foreach ($courses as $course) {
787 print_simple_box_start('center', '100%', '', 5, "coursebox");
788 $linkcss = '';
789 if (empty($course->visible)) {
790 $linkcss = 'class="dimmed"';
792 print_heading('<a title="'. format_string($course->fullname).'" '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>');
793 if (array_key_exists($course->id,$htmlarray)) {
794 foreach ($htmlarray[$course->id] as $modname => $html) {
795 echo $html;
798 print_simple_box_end();
803 function print_recent_activity($course) {
804 // $course is an object
805 // This function trawls through the logs looking for
806 // anything new since the user's last login
808 global $CFG, $USER, $SESSION;
810 $context = get_context_instance(CONTEXT_COURSE, $course->id);
812 $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
814 $timestart = round(time() - COURSE_MAX_RECENT_PERIOD, -2); // better db caching for guests - 100 seconds
816 if (!has_capability('moodle/legacy:guest', $context, NULL, false)) {
817 if (!empty($USER->lastcourseaccess[$course->id])) {
818 if ($USER->lastcourseaccess[$course->id] > $timestart) {
819 $timestart = $USER->lastcourseaccess[$course->id];
824 echo '<div class="activitydate">';
825 echo get_string('activitysince', '', userdate($timestart));
826 echo '</div>';
827 echo '<div class="activityhead">';
829 echo '<a href="'.$CFG->wwwroot.'/course/recent.php?id='.$course->id.'">'.get_string('recentactivityreport').'</a>';
831 echo "</div>\n";
833 $content = false;
835 /// Firstly, have there been any new enrolments?
837 $users = get_recent_enrolments($course->id, $timestart);
839 //Accessibility: new users now appear in an <OL> list.
840 if ($users) {
841 echo '<div class="newusers">';
842 print_headline(get_string("newusers").':', 3);
843 $content = true;
844 echo "<ol class=\"list\">\n";
845 foreach ($users as $user) {
846 $fullname = fullname($user, $viewfullnames);
847 echo '<li class="name"><a href="'."$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id\">$fullname</a></li>\n";
849 echo "</ol>\n</div>\n";
852 /// Next, have there been any modifications to the course structure?
854 $modinfo =& get_fast_modinfo($course);
856 $changelist = array();
858 $logs = get_records_select('log', "time > $timestart AND course = $course->id AND
859 module = 'course' AND
860 (action = 'add mod' OR action = 'update mod' OR action = 'delete mod')",
861 "id ASC");
863 if ($logs) {
864 $actions = array('add mod', 'update mod', 'delete mod');
865 $newgones = array(); // added and later deleted items
866 foreach ($logs as $key => $log) {
867 if (!in_array($log->action, $actions)) {
868 continue;
870 $info = split(' ', $log->info);
872 if ($info[0] == 'label') { // Labels are ignored in recent activity
873 continue;
876 if (count($info) != 2) {
877 debugging("Incorrect log entry info: id = ".$log->id, DEBUG_DEVELOPER);
878 continue;
881 $modname = $info[0];
882 $instanceid = $info[1];
884 if ($log->action == 'delete mod') {
885 // unfortunately we do not know if the mod was visible
886 if (!array_key_exists($log->info, $newgones)) {
887 $strdeleted = get_string('deletedactivity', 'moodle', get_string('modulename', $modname));
888 $changelist[$log->info] = array ('operation' => 'delete', 'text' => $strdeleted);
890 } else {
891 if (!isset($modinfo->instances[$modname][$instanceid])) {
892 if ($log->action == 'add mod') {
893 // do not display added and later deleted activities
894 $newgones[$log->info] = true;
896 continue;
898 $cm = $modinfo->instances[$modname][$instanceid];
899 if (!$cm->uservisible) {
900 continue;
903 if ($log->action == 'add mod') {
904 $stradded = get_string('added', 'moodle', get_string('modulename', $modname));
905 $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>");
907 } else if ($log->action == 'update mod' and empty($changelist[$log->info])) {
908 $strupdated = get_string('updated', 'moodle', get_string('modulename', $modname));
909 $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>");
915 if (!empty($changelist)) {
916 print_headline(get_string('courseupdates').':', 3);
917 $content = true;
918 foreach ($changelist as $changeinfo => $change) {
919 echo '<p class="activity">'.$change['text'].'</p>';
923 /// Now display new things from each module
925 $usedmodules = array();
926 foreach($modinfo->cms as $cm) {
927 if (isset($usedmodules[$cm->modname])) {
928 continue;
930 if (!$cm->uservisible) {
931 continue;
933 $usedmodules[$cm->modname] = $cm->modname;
936 foreach ($usedmodules as $modname) { // Each module gets it's own logs and prints them
937 if (file_exists($CFG->dirroot.'/mod/'.$modname.'/lib.php')) {
938 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
939 $print_recent_activity = $modname.'_print_recent_activity';
940 if (function_exists($print_recent_activity)) {
941 // NOTE: original $isteacher (second parameter below) was replaced with $viewfullnames!
942 $content = $print_recent_activity($course, $viewfullnames, $timestart) || $content;
944 } else {
945 debugging("Missing lib.php in lib/{$modname} - please reinstall files or uninstall the module");
949 if (! $content) {
950 echo '<p class="message">'.get_string('nothingnew').'</p>';
955 function get_array_of_activities($courseid) {
956 // For a given course, returns an array of course activity objects
957 // Each item in the array contains he following properties:
958 // cm - course module id
959 // mod - name of the module (eg forum)
960 // section - the number of the section (eg week or topic)
961 // name - the name of the instance
962 // visible - is the instance visible or not
963 // groupingid - grouping id
964 // groupmembersonly - is this instance visible to group members only
965 // extra - contains extra string to include in any link
967 global $CFG;
969 $mod = array();
971 if (!$rawmods = get_course_mods($courseid)) {
972 return $mod; // always return array
975 if ($sections = get_records("course_sections", "course", $courseid, "section ASC")) {
976 foreach ($sections as $section) {
977 if (!empty($section->sequence)) {
978 $sequence = explode(",", $section->sequence);
979 foreach ($sequence as $seq) {
980 if (empty($rawmods[$seq])) {
981 continue;
983 $mod[$seq]->id = $rawmods[$seq]->instance;
984 $mod[$seq]->cm = $rawmods[$seq]->id;
985 $mod[$seq]->mod = $rawmods[$seq]->modname;
986 $mod[$seq]->section = $section->section;
987 $mod[$seq]->visible = $rawmods[$seq]->visible;
988 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
989 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
990 $mod[$seq]->groupmembersonly = $rawmods[$seq]->groupmembersonly;
991 $mod[$seq]->extra = "";
993 $modname = $mod[$seq]->mod;
994 $functionname = $modname."_get_coursemodule_info";
996 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
997 continue;
1000 include_once("$CFG->dirroot/mod/$modname/lib.php");
1002 if (function_exists($functionname)) {
1003 if ($info = $functionname($rawmods[$seq])) {
1004 if (!empty($info->extra)) {
1005 $mod[$seq]->extra = $info->extra;
1007 if (!empty($info->icon)) {
1008 $mod[$seq]->icon = $info->icon;
1010 if (!empty($info->name)) {
1011 $mod[$seq]->name = urlencode($info->name);
1015 if (!isset($mod[$seq]->name)) {
1016 $mod[$seq]->name = urlencode(get_field($rawmods[$seq]->modname, "name", "id", $rawmods[$seq]->instance));
1022 return $mod;
1027 * Returns reference to full info about modules in course (including visibility).
1028 * Cached and as fast as possible (0 or 1 db query).
1029 * @param $course object or 'reset' string to reset caches, modinfo may be updated in db
1030 * @return mixed courseinfo object or nothing if resetting
1032 function &get_fast_modinfo(&$course, $userid=0) {
1033 global $CFG, $USER;
1035 static $cache = array();
1037 if ($course === 'reset') {
1038 $cache = array();
1039 $nothing = null;
1040 return $nothing; // we must return some reference
1043 if (empty($userid)) {
1044 $userid = $USER->id;
1047 if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
1048 return $cache[$course->id];
1051 if (empty($course->modinfo)) {
1052 // no modinfo yet - load it
1053 rebuild_course_cache($course->id);
1054 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
1057 $modinfo = new object();
1058 $modinfo->courseid = $course->id;
1059 $modinfo->userid = $userid;
1060 $modinfo->sections = array();
1061 $modinfo->cms = array();
1062 $modinfo->instances = array();
1063 $modinfo->groups = null; // loaded only when really needed - the only one db query
1065 $info = unserialize($course->modinfo);
1066 if (!is_array($info)) {
1067 // hmm, something is wrong - lets try to fix it
1068 rebuild_course_cache($course->id);
1069 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
1070 $info = unserialize($course->modinfo);
1071 if (!is_array($info)) {
1072 return $modinfo;
1076 if ($info) {
1077 // detect if upgrade required
1078 $first = reset($info);
1079 if (!isset($first->id)) {
1080 rebuild_course_cache($course->id);
1081 $course->modinfo = get_field('course', 'modinfo', 'id', $course->id);
1082 $info = unserialize($course->modinfo);
1083 if (!is_array($info)) {
1084 return $modinfo;
1089 $modlurals = array();
1091 $cmids = array();
1092 $contexts = null;
1093 foreach ($info as $mod) {
1094 $cmids[$mod->cm] = $mod->cm;
1096 if ($cmids) {
1097 // preload all module contexts with one query
1098 $contexts = get_context_instance(CONTEXT_MODULE, $cmids);
1101 foreach ($info as $mod) {
1102 if (empty($mod->name)) {
1103 // something is wrong here
1104 continue;
1106 // reconstruct minimalistic $cm
1107 $cm = new object();
1108 $cm->id = $mod->cm;
1109 $cm->instance = $mod->id;
1110 $cm->course = $course->id;
1111 $cm->modname = $mod->mod;
1112 $cm->name = urldecode($mod->name);
1113 $cm->visible = $mod->visible;
1114 $cm->sectionnum = $mod->section;
1115 $cm->groupmode = $mod->groupmode;
1116 $cm->groupingid = $mod->groupingid;
1117 $cm->groupmembersonly = $mod->groupmembersonly;
1118 $cm->extra = isset($mod->extra) ? urldecode($mod->extra) : '';
1119 $cm->icon = isset($mod->icon) ? $mod->icon : '';
1120 $cm->uservisible = true;
1122 // preload long names plurals and also check module is installed properly
1123 if (!isset($modlurals[$cm->modname])) {
1124 if (!file_exists("$CFG->dirroot/mod/$cm->modname/lib.php")) {
1125 continue;
1127 $modlurals[$cm->modname] = get_string('modulenameplural', $cm->modname);
1129 $cm->modplural = $modlurals[$cm->modname];
1131 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $contexts[$cm->id], $userid)) {
1132 $cm->uservisible = false;
1134 } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
1135 and !has_capability('moodle/site:accessallgroups', $contexts[$cm->id], $userid)) {
1136 if (is_null($modinfo->groups)) {
1137 $modinfo->groups = groups_get_user_groups($course->id, $userid);
1139 if (empty($modinfo->groups[$cm->groupingid])) {
1140 $cm->uservisible = false;
1144 if (!isset($modinfo->instances[$cm->modname])) {
1145 $modinfo->instances[$cm->modname] = array();
1147 $modinfo->instances[$cm->modname][$cm->instance] =& $cm;
1148 $modinfo->cms[$cm->id] =& $cm;
1150 // reconstruct sections
1151 if (!isset($modinfo->sections[$cm->sectionnum])) {
1152 $modinfo->sections[$cm->sectionnum] = array();
1154 $modinfo->sections[$cm->sectionnum][] = $cm->id;
1156 unset($cm);
1159 unset($cache[$course->id]); // prevent potential reference problems when switching users
1160 $cache[$course->id] = $modinfo;
1162 return $cache[$course->id];
1166 function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modnamesused) {
1167 // Returns a number of useful structures for course displays
1169 $mods = array(); // course modules indexed by id
1170 $modnames = array(); // all course module names (except resource!)
1171 $modnamesplural= array(); // all course module names (plural form)
1172 $modnamesused = array(); // course module names used
1174 if ($allmods = get_records("modules")) {
1175 foreach ($allmods as $mod) {
1176 if ($mod->visible) {
1177 $modnames[$mod->name] = get_string("modulename", "$mod->name");
1178 $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
1181 asort($modnames, SORT_LOCALE_STRING);
1182 } else {
1183 error("No modules are installed!");
1186 if ($rawmods = get_course_mods($courseid)) {
1187 foreach($rawmods as $mod) { // Index the mods
1188 if (empty($modnames[$mod->modname])) {
1189 continue;
1191 $mods[$mod->id] = $mod;
1192 $mods[$mod->id]->modfullname = $modnames[$mod->modname];
1193 if (!$mod->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE, $courseid))) {
1194 continue;
1196 // Check groupings
1197 if (!groups_course_module_visible($mod)) {
1198 continue;
1200 $modnamesused[$mod->modname] = $modnames[$mod->modname];
1202 if ($modnamesused) {
1203 asort($modnamesused, SORT_LOCALE_STRING);
1209 function get_all_sections($courseid) {
1211 return get_records("course_sections", "course", "$courseid", "section",
1212 "section, id, course, summary, sequence, visible");
1215 function course_set_display($courseid, $display=0) {
1216 global $USER;
1218 if ($display == "all" or empty($display)) {
1219 $display = 0;
1222 if (empty($USER->id) or $USER->username == 'guest') {
1223 //do not store settings in db for guests
1224 } else if (record_exists("course_display", "userid", $USER->id, "course", $courseid)) {
1225 set_field("course_display", "display", $display, "userid", $USER->id, "course", $courseid);
1226 } else {
1227 $record = new object();
1228 $record->userid = $USER->id;
1229 $record->course = $courseid;
1230 $record->display = $display;
1231 if (!insert_record("course_display", $record)) {
1232 notify("Could not save your course display!");
1236 return $USER->display[$courseid] = $display; // Note: = not ==
1239 function set_section_visible($courseid, $sectionnumber, $visibility) {
1240 /// For a given course section, markes it visible or hidden,
1241 /// and does the same for every activity in that section
1243 if ($section = get_record("course_sections", "course", $courseid, "section", $sectionnumber)) {
1244 set_field("course_sections", "visible", "$visibility", "id", $section->id);
1245 if (!empty($section->sequence)) {
1246 $modules = explode(",", $section->sequence);
1247 foreach ($modules as $moduleid) {
1248 set_coursemodule_visible($moduleid, $visibility, true);
1251 rebuild_course_cache($courseid);
1256 function print_section($course, $section, $mods, $modnamesused, $absolute=false, $width="100%") {
1257 /// Prints a section full of activity modules
1258 global $CFG, $USER;
1260 static $initialised;
1262 static $groupbuttons;
1263 static $groupbuttonslink;
1264 static $isediting;
1265 static $ismoving;
1266 static $strmovehere;
1267 static $strmovefull;
1268 static $strunreadpostsone;
1269 static $usetracking;
1270 static $groupings;
1273 if (!isset($initialised)) {
1274 $groupbuttons = ($course->groupmode or (!$course->groupmodeforce));
1275 $groupbuttonslink = (!$course->groupmodeforce);
1276 $isediting = isediting($course->id);
1277 $ismoving = $isediting && ismoving($course->id);
1278 if ($ismoving) {
1279 $strmovehere = get_string("movehere");
1280 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1282 include_once($CFG->dirroot.'/mod/forum/lib.php');
1283 if ($usetracking = forum_tp_can_track_forums()) {
1284 $strunreadpostsone = get_string('unreadpostsone', 'forum');
1286 $initialised = true;
1289 $labelformatoptions = new object();
1290 $labelformatoptions->noclean = true;
1292 /// Casting $course->modinfo to string prevents one notice when the field is null
1293 $modinfo = get_fast_modinfo($course);
1296 //Acccessibility: replace table with list <ul>, but don't output empty list.
1297 if (!empty($section->sequence)) {
1299 // Fix bug #5027, don't want style=\"width:$width\".
1300 echo "<ul class=\"section img-text\">\n";
1301 $sectionmods = explode(",", $section->sequence);
1303 foreach ($sectionmods as $modnumber) {
1304 if (empty($mods[$modnumber])) {
1305 continue;
1308 $mod = $mods[$modnumber];
1310 if ($ismoving and $mod->id == $USER->activitycopy) {
1311 // do not display moving mod
1312 continue;
1315 if (isset($modinfo->cms[$modnumber])) {
1316 if (!$modinfo->cms[$modnumber]->uservisible) {
1317 // visibility shortcut
1318 continue;
1320 } else {
1321 if (!file_exists("$CFG->dirroot/mod/$mod->modname/lib.php")) {
1322 // module not installed
1323 continue;
1325 if (!coursemodule_visible_for_user($mod)) {
1326 // full visibility check
1327 continue;
1331 echo '<li class="activity '.$mod->modname.'" id="module-'.$modnumber.'">'; // Unique ID
1332 if ($ismoving) {
1333 echo '<a title="'.$strmovefull.'"'.
1334 ' href="'.$CFG->wwwroot.'/course/mod.php?moveto='.$mod->id.'&amp;sesskey='.$USER->sesskey.'">'.
1335 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1336 ' alt="'.$strmovehere.'" /></a><br />
1340 if ($mod->indent) {
1341 print_spacer(12, 20 * $mod->indent, false);
1344 $extra = '';
1345 if (!empty($modinfo->cms[$modnumber]->extra)) {
1346 $extra = $modinfo->cms[$modnumber]->extra;
1349 if ($mod->modname == "label") {
1350 if (!$mod->visible) {
1351 echo "<div class=\"dimmed_text\">";
1353 echo format_text($extra, FORMAT_HTML, $labelformatoptions);
1354 if (!$mod->visible) {
1355 echo "</div>";
1357 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1358 if (!isset($groupings)) {
1359 $groupings = groups_get_all_groupings($course->id);
1361 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1364 } else { // Normal activity
1365 $instancename = format_string($modinfo->cms[$modnumber]->name, true, $course->id);
1367 if (!empty($modinfo->cms[$modnumber]->icon)) {
1368 $icon = "$CFG->pixpath/".$modinfo->cms[$modnumber]->icon;
1369 } else {
1370 $icon = "$CFG->modpixpath/$mod->modname/icon.gif";
1373 //Accessibility: for files get description via icon.
1374 $altname = '';
1375 if ('resource'==$mod->modname) {
1376 if (!empty($modinfo->cms[$modnumber]->icon)) {
1377 $possaltname = $modinfo->cms[$modnumber]->icon;
1379 $mimetype = mimeinfo_from_icon('type', $possaltname);
1380 $altname = get_mimetype_description($mimetype);
1381 } else {
1382 $altname = $mod->modfullname;
1384 } else {
1385 $altname = $mod->modfullname;
1387 // Avoid unnecessary duplication.
1388 if (false!==stripos($instancename, $altname)) {
1389 $altname = '';
1391 // File type after name, for alphabetic lists (screen reader).
1392 if ($altname) {
1393 $altname = get_accesshide(' '.$altname);
1396 $linkcss = $mod->visible ? "" : " class=\"dimmed\" ";
1397 echo '<a '.$linkcss.' '.$extra. // Title unnecessary!
1398 ' href="'.$CFG->wwwroot.'/mod/'.$mod->modname.'/view.php?id='.$mod->id.'">'.
1399 '<img src="'.$icon.'" class="activityicon" alt="" /> <span>'.
1400 $instancename.$altname.'</span></a>';
1402 if (!empty($CFG->enablegroupings) && !empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) {
1403 if (!isset($groupings)) {
1404 $groupings = groups_get_all_groupings($course->id);
1406 echo " <span class=\"groupinglabel\">(".format_string($groupings[$mod->groupingid]->name).')</span>';
1409 if ($usetracking && $mod->modname == 'forum') {
1410 if ($unread = forum_tp_count_forum_unread_posts($mod, $course)) {
1411 echo '<span class="unread"> <a href="'.$CFG->wwwroot.'/mod/forum/view.php?id='.$mod->id.'">';
1412 if ($unread == 1) {
1413 echo $strunreadpostsone;
1414 } else {
1415 print_string('unreadpostsnumber', 'forum', $unread);
1417 echo '</a></span>';
1421 if ($isediting) {
1422 // TODO: we must define this as mod property!
1423 if ($groupbuttons and $mod->modname != 'label' and $mod->modname != 'resource' and $mod->modname != 'glossary') {
1424 if (! $mod->groupmodelink = $groupbuttonslink) {
1425 $mod->groupmode = $course->groupmode;
1428 } else {
1429 $mod->groupmode = false;
1431 echo '&nbsp;&nbsp;';
1432 echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section);
1434 echo "</li>\n";
1437 } elseif ($ismoving) {
1438 echo "<ul class=\"section\">\n";
1441 if ($ismoving) {
1442 echo '<li><a title="'.$strmovefull.'"'.
1443 ' href="'.$CFG->wwwroot.'/course/mod.php?movetosection='.$section->id.'&amp;sesskey='.$USER->sesskey.'">'.
1444 '<img class="movetarget" src="'.$CFG->pixpath.'/movehere.gif" '.
1445 ' alt="'.$strmovehere.'" /></a></li>
1448 if (!empty($section->sequence) || $ismoving) {
1449 echo "</ul><!--class='section'-->\n\n";
1454 * Prints the menus to add activities and resources.
1456 function print_section_add_menus($course, $section, $modnames, $vertical=false, $return=false) {
1457 global $CFG;
1459 // check to see if user can add menus
1460 if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) {
1461 return false;
1464 static $resources = false;
1465 static $activities = false;
1467 if ($resources === false) {
1468 $resources = array();
1469 $activities = array();
1471 foreach($modnames as $modname=>$modnamestr) {
1472 if (!course_allowed_module($course, $modname)) {
1473 continue;
1476 $libfile = "$CFG->dirroot/mod/$modname/lib.php";
1477 if (!file_exists($libfile)) {
1478 continue;
1480 include_once($libfile);
1481 $gettypesfunc = $modname.'_get_types';
1482 if (function_exists($gettypesfunc)) {
1483 $types = $gettypesfunc();
1484 foreach($types as $type) {
1485 if (!isset($type->modclass) or !isset($type->typestr)) {
1486 debugging('Incorrect activity type in '.$modname);
1487 continue;
1489 if ($type->modclass == MOD_CLASS_RESOURCE) {
1490 $resources[$type->type] = $type->typestr;
1491 } else {
1492 $activities[$type->type] = $type->typestr;
1495 } else {
1496 // all mods without type are considered activity
1497 $activities[$modname] = $modnamestr;
1502 $straddactivity = get_string('addactivity');
1503 $straddresource = get_string('addresource');
1505 $output = '<div class="section_add_menus">';
1507 if (!$vertical) {
1508 $output .= '<div class="horizontal">';
1511 if (!empty($resources)) {
1512 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1513 $resources, "ressection$section", "", $straddresource, 'resource/types', $straddresource, true);
1516 if (!empty($activities)) {
1517 $output .= ' ';
1518 $output .= popup_form("$CFG->wwwroot/course/mod.php?id=$course->id&amp;section=$section&amp;sesskey=".sesskey()."&amp;add=",
1519 $activities, "section$section", "", $straddactivity, 'mods', $straddactivity, true);
1522 if (!$vertical) {
1523 $output .= '</div>';
1526 $output .= '</div>';
1528 if ($return) {
1529 return $output;
1530 } else {
1531 echo $output;
1536 * Rebuilds the cached list of course activities stored in the database
1537 * @param int $courseid - id of course to rebuil, empty means all
1538 * @param boolean $clearonly - only clear the modinfo fields, gets rebuild automatically on the fly
1540 function rebuild_course_cache($courseid=0, $clearonly=false) {
1541 global $COURSE;
1543 if ($clearonly) {
1544 $courseselect = empty($courseid) ? "" : "id = $courseid";
1545 set_field_select('course', 'modinfo', null, $courseselect);
1546 // update cached global COURSE too ;-)
1547 if ($courseid == $COURSE->id) {
1548 $COURSE->modinfo = null;
1550 // reset the fast modinfo cache
1551 $reset = 'reset';
1552 get_fast_modinfo($reset);
1553 return;
1556 if ($courseid) {
1557 $select = "id = '$courseid'";
1558 } else {
1559 $select = "";
1560 @set_time_limit(0); // this could take a while! MDL-10954
1563 if ($rs = get_recordset_select("course", $select,'','id,fullname')) {
1564 while($course = rs_fetch_next_record($rs)) {
1565 $modinfo = serialize(get_array_of_activities($course->id));
1566 if (!set_field("course", "modinfo", $modinfo, "id", $course->id)) {
1567 notify("Could not cache module information for course '" . format_string($course->fullname) . "'!");
1569 // update cached global COURSE too ;-)
1570 if ($course->id == $COURSE->id) {
1571 $COURSE->modinfo = $modinfo;
1574 rs_close($rs);
1576 // reset the fast modinfo cache
1577 $reset = 'reset';
1578 get_fast_modinfo($reset);
1581 function get_child_categories($parent) {
1582 /// Returns an array of the children categories for the given category
1583 /// ID by caching all of the categories in a static hash
1585 static $allcategories = null;
1587 // only fill in this variable the first time
1588 if (null == $allcategories) {
1589 $allcategories = array();
1591 $categories = get_categories();
1592 foreach ($categories as $category) {
1593 if (empty($allcategories[$category->parent])) {
1594 $allcategories[$category->parent] = array();
1596 $allcategories[$category->parent][] = $category;
1600 if (empty($allcategories[$parent])) {
1601 return array();
1602 } else {
1603 return $allcategories[$parent];
1608 function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
1609 /// Given an empty array, this function recursively travels the
1610 /// categories, building up a nice list for display. It also makes
1611 /// an array that list all the parents for each category.
1613 // initialize the arrays if needed
1614 if (!is_array($list)) {
1615 $list = array();
1617 if (!is_array($parents)) {
1618 $parents = array();
1621 if ($category) {
1622 if ($path) {
1623 $path = $path.' / '.format_string($category->name);
1624 } else {
1625 $path = format_string($category->name);
1627 $list[$category->id] = $path;
1628 } else {
1629 $category->id = 0;
1632 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
1633 foreach ($categories as $cat) {
1634 if (!empty($category->id)) {
1635 if (isset($parents[$category->id])) {
1636 $parents[$cat->id] = $parents[$category->id];
1638 $parents[$cat->id][] = $category->id;
1640 make_categories_list($list, $parents, $cat, $path);
1646 function print_whole_category_list($category=NULL, $displaylist=NULL, $parentslist=NULL, $depth=-1, $files = true) {
1647 /// Recursive function to print out all the categories in a nice format
1648 /// with or without courses included
1649 global $CFG;
1651 if (isset($CFG->max_category_depth) && ($depth >= $CFG->max_category_depth)) {
1652 return;
1655 if (!$displaylist) {
1656 make_categories_list($displaylist, $parentslist);
1659 if ($category) {
1660 if ($category->visible or has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
1661 print_category_info($category, $depth, $files);
1662 } else {
1663 return; // Don't bother printing children of invisible categories
1666 } else {
1667 $category->id = "0";
1670 if ($categories = get_child_categories($category->id)) { // Print all the children recursively
1671 $countcats = count($categories);
1672 $count = 0;
1673 $first = true;
1674 $last = false;
1675 foreach ($categories as $cat) {
1676 $count++;
1677 if ($count == $countcats) {
1678 $last = true;
1680 $up = $first ? false : true;
1681 $down = $last ? false : true;
1682 $first = false;
1684 print_whole_category_list($cat, $displaylist, $parentslist, $depth + 1, $files);
1689 // this function will return $options array for choose_from_menu, with whitespace to denote nesting.
1691 function make_categories_options() {
1692 make_categories_list($cats,$parents);
1693 foreach ($cats as $key => $value) {
1694 if (array_key_exists($key,$parents)) {
1695 if ($indent = count($parents[$key])) {
1696 for ($i = 0; $i < $indent; $i++) {
1697 $cats[$key] = '&nbsp;'.$cats[$key];
1702 return $cats;
1705 function print_category_info($category, $depth, $files = false) {
1706 /// Prints the category info in indented fashion
1707 /// This function is only used by print_whole_category_list() above
1709 global $CFG;
1710 static $strallowguests, $strrequireskey, $strsummary;
1712 if (empty($strsummary)) {
1713 $strallowguests = get_string('allowguests');
1714 $strrequireskey = get_string('requireskey');
1715 $strsummary = get_string('summary');
1718 $catlinkcss = $category->visible ? '' : ' class="dimmed" ';
1720 $coursecount = count_records('course') <= FRONTPAGECOURSELIMIT;
1721 if ($files and $coursecount) {
1722 $catimage = '<img src="'.$CFG->pixpath.'/i/course.gif" alt="" />';
1723 } else {
1724 $catimage = "&nbsp;";
1727 echo "\n\n".'<table class="categorylist">';
1729 $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');
1730 if ($files and $coursecount) {
1732 echo '<tr>';
1734 if ($depth) {
1735 $indent = $depth*30;
1736 $rows = count($courses) + 1;
1737 echo '<td rowspan="'.$rows.'" valign="top" width="'.$indent.'">';
1738 print_spacer(10, $indent);
1739 echo '</td>';
1742 echo '<td valign="top" class="category image">'.$catimage.'</td>';
1743 echo '<td valign="top" class="category name">';
1744 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1745 echo '</td>';
1746 echo '<td class="category info">&nbsp;</td>';
1747 echo '</tr>';
1749 if ($courses && !(isset($CFG->max_category_depth)&&($depth>=$CFG->max_category_depth-1))) {
1750 foreach ($courses as $course) {
1751 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1752 echo '<tr><td valign="top">&nbsp;';
1753 echo '</td><td valign="top" class="course name">';
1754 echo '<a '.$linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'. format_string($course->fullname).'</a>';
1755 echo '</td><td align="right" valign="top" class="course info">';
1756 if ($course->guest ) {
1757 echo '<a title="'.$strallowguests.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1758 echo '<img alt="'.$strallowguests.'" src="'.$CFG->pixpath.'/i/guest.gif" /></a>';
1759 } else {
1760 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1762 if ($course->password) {
1763 echo '<a title="'.$strrequireskey.'" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">';
1764 echo '<img alt="'.$strrequireskey.'" src="'.$CFG->pixpath.'/i/key.gif" /></a>';
1765 } else {
1766 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1768 if ($course->summary) {
1769 link_to_popup_window ('/course/info.php?id='.$course->id, 'courseinfo',
1770 '<img alt="'.$strsummary.'" src="'.$CFG->pixpath.'/i/info.gif" />',
1771 400, 500, $strsummary);
1772 } else {
1773 echo '<img alt="" style="width:18px;height:16px;" src="'.$CFG->pixpath.'/spacer.gif" />';
1775 echo '</td></tr>';
1778 } else {
1780 echo '<tr>';
1782 if ($depth) {
1783 $indent = $depth*20;
1784 echo '<td valign="top" width="'.$indent.'">';
1785 print_spacer(10, $indent);
1786 echo '</td>';
1789 echo '<td valign="top" class="category name">';
1790 echo '<a '.$catlinkcss.' href="'.$CFG->wwwroot.'/course/category.php?id='.$category->id.'">'. format_string($category->name).'</a>';
1791 echo '</td>';
1792 echo '<td valign="top" class="category number">';
1793 if (count($courses)) {
1794 echo count($courses);
1796 echo '</td></tr>';
1798 echo '</table>';
1803 function print_courses($category) {
1804 /// Category is 0 (for all courses) or an object
1806 global $CFG;
1808 if (!is_object($category) && $category==0) {
1809 $categories = get_child_categories(0); // Parent = 0 ie top-level categories only
1810 if (is_array($categories) && count($categories) == 1) {
1811 $category = array_shift($categories);
1812 $courses = get_courses_wmanagers($category->id,
1813 'c.sortorder ASC',
1814 array('password','summary','currency'));
1815 } else {
1816 $courses = get_courses_wmanagers('all',
1817 'c.sortorder ASC',
1818 array('password','summary','currency'));
1820 unset($categories);
1821 } else {
1822 $courses = get_courses_wmanagers($category->id,
1823 'c.sortorder ASC',
1824 array('password','summary','currency'));
1827 if ($courses) {
1828 echo '<ul class="unlist">';
1829 foreach ($courses as $course) {
1830 if ($course->visible == 1
1831 || has_capability('moodle/course:viewhiddencourses',$course->context)) {
1832 echo '<li>';
1833 print_course($course);
1834 echo "</li>\n";
1837 echo "</ul>\n";
1838 } else {
1839 print_heading(get_string("nocoursesyet"));
1840 $context = get_context_instance(CONTEXT_SYSTEM);
1841 if (has_capability('moodle/course:create', $context)) {
1842 $options = array();
1843 $options['category'] = $category->id;
1844 echo '<div class="addcoursebutton">';
1845 print_single_button($CFG->wwwroot.'/course/edit.php', $options, get_string("addnewcourse"));
1846 echo '</div>';
1855 function print_course($course) {
1857 global $CFG, $USER;
1859 if (isset($course->context)) {
1860 $context = $course->context;
1861 } else {
1862 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1865 $linkcss = $course->visible ? '' : ' class="dimmed" ';
1867 echo '<div class="coursebox clearfix">';
1868 echo '<div class="info">';
1869 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
1870 $linkcss.' href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.
1871 format_string($course->fullname).'</a></div>';
1873 /// first find all roles that are supposed to be displayed
1875 if (!empty($CFG->coursemanager)) {
1876 $managerroles = split(',', $CFG->coursemanager);
1877 $canseehidden = has_capability('moodle/role:viewhiddenassigns', $context);
1878 $namesarray = array();
1879 if (isset($course->managers)) {
1880 if (count($course->managers)) {
1881 $rusers = $course->managers;
1882 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1884 /// Rename some of the role names if needed
1885 if (isset($context)) {
1886 $aliasnames = get_records('role_names', 'contextid', $context->id,'','roleid,contextid,name');
1889 // keep a note of users displayed to eliminate duplicates
1890 $usersshown = array();
1891 foreach ($rusers as $ra) {
1893 // if we've already displayed user don't again
1894 if (in_array($ra->user->id,$usersshown)) {
1895 continue;
1897 $usersshown[] = $ra->user->id;
1899 if ($ra->hidden == 0 || $canseehidden) {
1900 $fullname = fullname($ra->user, $canviewfullnames);
1901 if ($ra->hidden == 1) {
1902 $status = " <img src=\"{$CFG->pixpath}/t/show.gif\" title=\"".get_string('userhashiddenassignments', 'role')."\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
1903 } else {
1904 $status = '';
1907 if (isset($aliasnames[$ra->roleid])) {
1908 $ra->rolename = $aliasnames[$ra->roleid]->name;
1911 $namesarray[] = format_string($ra->rolename)
1912 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$ra->user->id.'&amp;course='.SITEID.'">'
1913 . $fullname . '</a>' . $status;
1917 } else {
1918 $rusers = get_role_users($managerroles, $context,
1919 true, '', 'r.sortorder ASC, u.lastname ASC', $canseehidden);
1920 if (is_array($rusers) && count($rusers)) {
1921 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
1922 foreach ($rusers as $teacher) {
1923 $fullname = fullname($teacher, $canviewfullnames);
1924 $namesarray[] = format_string($teacher->rolename)
1925 . ': <a href="'.$CFG->wwwroot.'/user/view.php?id='.$teacher->id.'&amp;course='.SITEID.'">'
1926 . $fullname . '</a>';
1931 if (!empty($namesarray)) {
1932 echo "<ul class=\"teachers\">\n<li>";
1933 echo implode('</li><li>', $namesarray);
1934 echo "</li></ul>";
1938 require_once("$CFG->dirroot/enrol/enrol.class.php");
1939 $enrol = enrolment_factory::factory($course->enrol);
1940 echo $enrol->get_access_icons($course);
1942 echo '</div><div class="summary">';
1943 $options = NULL;
1944 $options->noclean = true;
1945 $options->para = false;
1946 echo format_text($course->summary, FORMAT_MOODLE, $options, $course->id);
1947 echo '</div>';
1948 echo '</div>';
1952 function print_my_moodle() {
1953 /// Prints custom user information on the home page.
1954 /// Over time this can include all sorts of information
1956 global $USER, $CFG;
1958 if (empty($USER->id)) {
1959 error("It shouldn't be possible to see My Moodle without being logged in.");
1962 $courses = get_my_courses($USER->id, 'visible DESC,sortorder ASC', array('summary'));
1963 $rhosts = array();
1964 $rcourses = array();
1965 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1966 $rcourses = get_my_remotecourses($USER->id);
1967 $rhosts = get_my_remotehosts();
1970 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1972 if (!empty($courses)) {
1973 echo '<ul class="unlist">';
1974 foreach ($courses as $course) {
1975 if ($course->id == SITEID) {
1976 continue;
1978 echo '<li>';
1979 print_course($course, "100%");
1980 echo "</li>\n";
1982 echo "</ul>\n";
1985 // MNET
1986 if (!empty($rcourses)) {
1987 // at the IDP, we know of all the remote courses
1988 foreach ($rcourses as $course) {
1989 print_remote_course($course, "100%");
1991 } elseif (!empty($rhosts)) {
1992 // non-IDP, we know of all the remote servers, but not courses
1993 foreach ($rhosts as $host) {
1994 print_remote_host($host, "100%");
1997 unset($course);
1998 unset($host);
2000 if (count_records("course") > (count($courses) + 1) ) { // Some courses not being displayed
2001 echo "<table width=\"100%\"><tr><td align=\"center\">";
2002 print_course_search("", false, "short");
2003 echo "</td><td align=\"center\">";
2004 print_single_button("$CFG->wwwroot/course/index.php", NULL, get_string("fulllistofcourses"), "get");
2005 echo "</td></tr></table>\n";
2008 } else {
2009 if (count_records("course_categories") > 1) {
2010 print_simple_box_start("center", "100%", "#FFFFFF", 5, "categorybox");
2011 print_whole_category_list();
2012 print_simple_box_end();
2013 } else {
2014 print_courses(0);
2020 function print_course_search($value="", $return=false, $format="plain") {
2022 global $CFG;
2023 static $count = 0;
2025 $count++;
2027 $id = 'coursesearch';
2029 if ($count > 1) {
2030 $id .= $count;
2033 $strsearchcourses= get_string("searchcourses");
2035 if ($format == 'plain') {
2036 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2037 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2038 $output .= '<label for="coursesearchbox">'.$strsearchcourses.': </label>';
2039 $output .= '<input type="text" id="coursesearchbox" size="30" name="search" value="'.s($value, true).'" />';
2040 $output .= '<input type="submit" value="'.get_string('go').'" />';
2041 $output .= '</fieldset></form>';
2042 } else if ($format == 'short') {
2043 $output = '<form id="'.$id.'" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2044 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2045 $output .= '<label for="shortsearchbox">'.$strsearchcourses.': </label>';
2046 $output .= '<input type="text" id="shortsearchbox" size="12" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2047 $output .= '<input type="submit" value="'.get_string('go').'" />';
2048 $output .= '</fieldset></form>';
2049 } else if ($format == 'navbar') {
2050 $output = '<form id="coursesearchnavbar" action="'.$CFG->wwwroot.'/course/search.php" method="get">';
2051 $output .= '<fieldset class="coursesearchbox invisiblefieldset">';
2052 $output .= '<label for="navsearchbox">'.$strsearchcourses.': </label>';
2053 $output .= '<input type="text" id="navsearchbox" size="20" name="search" alt="'.s($strsearchcourses).'" value="'.s($value, true).'" />';
2054 $output .= '<input type="submit" value="'.get_string('go').'" />';
2055 $output .= '</fieldset></form>';
2058 if ($return) {
2059 return $output;
2061 echo $output;
2064 function print_remote_course($course, $width="100%") {
2066 global $CFG, $USER;
2068 $linkcss = '';
2070 $url = "{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$course->hostid}&amp;wantsurl=/course/view.php?id={$course->remoteid}";
2072 echo '<div class="coursebox remotecoursebox clearfix">';
2073 echo '<div class="info">';
2074 echo '<div class="name"><a title="'.get_string('entercourse').'"'.
2075 $linkcss.' href="'.$url.'">'
2076 . format_string($course->fullname) .'</a><br />'
2077 . format_string($course->hostname) . ' : '
2078 . format_string($course->cat_name) . ' : '
2079 . format_string($course->shortname). '</div>';
2080 echo '</div><div class="summary">';
2081 $options = NULL;
2082 $options->noclean = true;
2083 $options->para = false;
2084 echo format_text($course->summary, FORMAT_MOODLE, $options);
2085 echo '</div>';
2086 echo '</div>';
2089 function print_remote_host($host, $width="100%") {
2091 global $CFG, $USER;
2093 $linkcss = '';
2095 echo '<div class="coursebox clearfix">';
2096 echo '<div class="info">';
2097 echo '<div class="name">';
2098 echo '<img src="'.$CFG->pixpath.'/i/mnethost.gif" class="icon" alt="'.get_string('course').'" />';
2099 echo '<a title="'.s($host['name']).'" href="'.s($host['url']).'">'
2100 . s($host['name']).'</a> - ';
2101 echo $host['count'] . ' ' . get_string('courses');
2102 echo '</div>';
2103 echo '</div>';
2104 echo '</div>';
2108 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
2110 function add_course_module($mod) {
2112 $mod->added = time();
2113 unset($mod->id);
2115 return insert_record("course_modules", $mod);
2119 * Returns course section - creates new if does not exist yet.
2120 * @param int $relative section number
2121 * @param int $courseid
2122 * @return object $course_section object
2124 function get_course_section($section, $courseid) {
2125 if ($cw = get_record("course_sections", "section", $section, "course", $courseid)) {
2126 return $cw;
2128 $cw = new object();
2129 $cw->course = $courseid;
2130 $cw->section = $section;
2131 $cw->summary = "";
2132 $cw->sequence = "";
2133 $id = insert_record("course_sections", $cw);
2134 return get_record("course_sections", "id", $id);
2137 * Given a full mod object with section and course already defined, adds this module to that section.
2139 * @param object $mod
2140 * @param int $beforemod An existing ID which we will insert the new module before
2141 * @return int The course_sections ID where the mod is inserted
2143 function add_mod_to_section($mod, $beforemod=NULL) {
2145 if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
2147 $section->sequence = trim($section->sequence);
2149 if (empty($section->sequence)) {
2150 $newsequence = "$mod->coursemodule";
2152 } else if ($beforemod) {
2153 $modarray = explode(",", $section->sequence);
2155 if ($key = array_keys ($modarray, $beforemod->id)) {
2156 $insertarray = array($mod->id, $beforemod->id);
2157 array_splice($modarray, $key[0], 1, $insertarray);
2158 $newsequence = implode(",", $modarray);
2160 } else { // Just tack it on the end anyway
2161 $newsequence = "$section->sequence,$mod->coursemodule";
2164 } else {
2165 $newsequence = "$section->sequence,$mod->coursemodule";
2168 if (set_field("course_sections", "sequence", $newsequence, "id", $section->id)) {
2169 return $section->id; // Return course_sections ID that was used.
2170 } else {
2171 return 0;
2174 } else { // Insert a new record
2175 $section->course = $mod->course;
2176 $section->section = $mod->section;
2177 $section->summary = "";
2178 $section->sequence = $mod->coursemodule;
2179 return insert_record("course_sections", $section);
2183 function set_coursemodule_groupmode($id, $groupmode) {
2184 return set_field("course_modules", "groupmode", $groupmode, "id", $id);
2187 function set_coursemodule_groupingid($id, $groupingid) {
2188 return set_field("course_modules", "groupingid", $groupingid, "id", $id);
2191 function set_coursemodule_groupmembersonly($id, $groupmembersonly) {
2192 return set_field("course_modules", "groupmembersonly", $groupmembersonly, "id", $id);
2195 function set_coursemodule_idnumber($id, $idnumber) {
2196 return set_field("course_modules", "idnumber", $idnumber, "id", $id);
2199 * $prevstateoverrides = true will set the visibility of the course module
2200 * to what is defined in visibleold. This enables us to remember the current
2201 * visibility when making a whole section hidden, so that when we toggle
2202 * that section back to visible, we are able to return the visibility of
2203 * the course module back to what it was originally.
2205 function set_coursemodule_visible($id, $visible, $prevstateoverrides=false) {
2206 if (!$cm = get_record('course_modules', 'id', $id)) {
2207 return false;
2209 if (!$modulename = get_field('modules', 'name', 'id', $cm->module)) {
2210 return false;
2212 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2213 foreach($events as $event) {
2214 if ($visible) {
2215 show_event($event);
2216 } else {
2217 hide_event($event);
2221 if ($prevstateoverrides) {
2222 if ($visible == '0') {
2223 // Remember the current visible state so we can toggle this back.
2224 set_field('course_modules', 'visibleold', $cm->visible, 'id', $id);
2225 } else {
2226 // Get the previous saved visible states.
2227 return set_field('course_modules', 'visible', $cm->visibleold, 'id', $id);
2230 return set_field("course_modules", "visible", $visible, "id", $id);
2234 * Delete a course module and any associated data at the course level (events)
2235 * Until 1.5 this function simply marked a deleted flag ... now it
2236 * deletes it completely.
2239 function delete_course_module($id) {
2240 global $CFG;
2241 require_once($CFG->libdir.'/gradelib.php');
2243 if (!$cm = get_record('course_modules', 'id', $id)) {
2244 return true;
2246 $modulename = get_field('modules', 'name', 'id', $cm->module);
2247 //delete events from calendar
2248 if ($events = get_records_select('event', "instance = '$cm->instance' AND modulename = '$modulename'")) {
2249 foreach($events as $event) {
2250 delete_event($event->id);
2253 //delete grade items, outcome items and grades attached to modules
2254 if ($grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename,
2255 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course))) {
2256 foreach ($grade_items as $grade_item) {
2257 $grade_item->delete('moddelete');
2261 return delete_records('course_modules', 'id', $cm->id);
2264 function delete_mod_from_section($mod, $section) {
2266 if ($section = get_record("course_sections", "id", "$section") ) {
2268 $modarray = explode(",", $section->sequence);
2270 if ($key = array_keys ($modarray, $mod)) {
2271 array_splice($modarray, $key[0], 1);
2272 $newsequence = implode(",", $modarray);
2273 return set_field("course_sections", "sequence", $newsequence, "id", $section->id);
2274 } else {
2275 return false;
2279 return false;
2283 * Moves a section up or down by 1. CANNOT BE USED DIRECTLY BY AJAX!
2285 * @param object $course
2286 * @param int $section
2287 * @param int $move (-1 or 1)
2289 function move_section($course, $section, $move) {
2290 /// Moves a whole course section up and down within the course
2291 global $USER;
2293 if (!$move) {
2294 return true;
2297 $sectiondest = $section + $move;
2299 if ($sectiondest > $course->numsections or $sectiondest < 1) {
2300 return false;
2303 if (!$sectionrecord = get_record("course_sections", "course", $course->id, "section", $section)) {
2304 return false;
2307 if (!$sectiondestrecord = get_record("course_sections", "course", $course->id, "section", $sectiondest)) {
2308 return false;
2312 $count = abs($sectiondest - $section);
2313 $direction = ($sectiondest - $section) / $count;
2315 for ($i = 0, $ref = $section + $direction; $i < $count; ++$i, $ref += $direction) {
2316 if (!set_field("course_sections", "section", $ref - $direction, 'course', $course->id, 'section', $ref)) {
2317 return false;
2321 if (!set_field("course_sections", "section", $sectiondest, "id", $sectionrecord->id)) {
2322 return false;
2325 // if the focus is on the section that is being moved, then move the focus along
2326 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2327 course_set_display($course->id, $sectiondest);
2330 // Check for duplicates and fix order if needed.
2331 // There is a very rare case that some sections in the same course have the same section id.
2332 $sections = get_records_select('course_sections', "course = $course->id", 'section ASC');
2333 $n = 0;
2334 foreach ($sections as $section) {
2335 if ($section->section != $n) {
2336 if (!set_field('course_sections', 'section', $n, 'id', $section->id)) {
2337 return false;
2340 $n++;
2342 return true;
2346 * Moves a section within a course, from a position to another.
2347 * Be very careful: $section and $destination refer to section number,
2348 * not id!.
2350 * @param object $course
2351 * @param int $section Section number (not id!!!)
2352 * @param int $destination
2353 * @return boolean Result
2355 function move_section_to($course, $section, $destination) {
2356 /// Moves a whole course section up and down within the course
2357 global $USER;
2359 if (!$destination) {
2360 return true;
2363 if ($destination > $course->numsections or $destination < 1) {
2364 return false;
2367 // Get all sections for this course and re-order them (2 of them should now share the same section number)
2368 if (!$sections = get_records_menu('course_sections', 'course',$course->id, 'section ASC, id ASC', 'id, section')) {
2369 return false;
2372 $sections = reorder_sections($sections, $section, $destination);
2374 // Update all sections
2375 foreach ($sections as $id => $position) {
2376 set_field('course_sections', 'section', $position, 'id', $id);
2379 // if the focus is on the section that is being moved, then move the focus along
2380 if (isset($USER->display[$course->id]) and ($USER->display[$course->id] == $section)) {
2381 course_set_display($course->id, $destination);
2383 return true;
2387 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
2388 * an original position number and a target position number, rebuilds the array so that the
2389 * move is made without any duplication of section positions.
2390 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
2391 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
2393 * @param array $sections
2394 * @param int $origin_position
2395 * @param int $target_position
2396 * @return array
2398 function reorder_sections($sections, $origin_position, $target_position) {
2399 if (!is_array($sections)) {
2400 return false;
2403 // We can't move section position 0
2404 if ($origin_position < 1) {
2405 echo "We can't move section position 0";
2406 return false;
2409 // Locate origin section in sections array
2410 if (!$origin_key = array_search($origin_position, $sections)) {
2411 echo "searched position not in sections array";
2412 return false; // searched position not in sections array
2415 // Extract origin section
2416 $origin_section = $sections[$origin_key];
2417 unset($sections[$origin_key]);
2419 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
2420 $found = false;
2421 $append_array = array();
2422 foreach ($sections as $id => $position) {
2423 if ($found) {
2424 $append_array[$id] = $position;
2425 unset($sections[$id]);
2427 if ($position == $target_position) {
2428 $found = true;
2432 // Append moved section
2433 $sections[$origin_key] = $origin_section;
2435 // Append rest of array (if applicable)
2436 if (!empty($append_array)) {
2437 foreach ($append_array as $id => $position) {
2438 $sections[$id] = $position;
2442 // Renumber positions
2443 $position = 0;
2444 foreach ($sections as $id => $p) {
2445 $sections[$id] = $position;
2446 $position++;
2449 return $sections;
2453 function moveto_module($mod, $section, $beforemod=NULL) {
2454 /// All parameters are objects
2455 /// Move the module object $mod to the specified $section
2456 /// If $beforemod exists then that is the module
2457 /// before which $modid should be inserted
2459 /// Remove original module from original section
2461 if (! delete_mod_from_section($mod->id, $mod->section)) {
2462 notify("Could not delete module from existing section");
2465 /// Update module itself if necessary
2467 if ($mod->section != $section->id) {
2468 $mod->section = $section->id;
2469 if (!update_record("course_modules", $mod)) {
2470 return false;
2472 // if moving to a hidden section then hide module
2473 if (!$section->visible) {
2474 set_coursemodule_visible($mod->id, 0);
2478 /// Add the module into the new section
2480 $mod->course = $section->course;
2481 $mod->section = $section->section; // need relative reference
2482 $mod->coursemodule = $mod->id;
2484 if (! add_mod_to_section($mod, $beforemod)) {
2485 return false;
2488 return true;
2492 function make_editing_buttons($mod, $absolute=false, $moveselect=true, $indent=-1, $section=-1) {
2493 global $CFG, $USER;
2495 static $str;
2496 static $sesskey;
2498 $modcontext = get_context_instance(CONTEXT_MODULE, $mod->id);
2499 // no permission to edit
2500 if (!has_capability('moodle/course:manageactivities', $modcontext)) {
2501 return false;
2504 if (!isset($str)) {
2505 $str->delete = get_string("delete");
2506 $str->move = get_string("move");
2507 $str->moveup = get_string("moveup");
2508 $str->movedown = get_string("movedown");
2509 $str->moveright = get_string("moveright");
2510 $str->moveleft = get_string("moveleft");
2511 $str->update = get_string("update");
2512 $str->duplicate = get_string("duplicate");
2513 $str->hide = get_string("hide");
2514 $str->show = get_string("show");
2515 $str->clicktochange = get_string("clicktochange");
2516 $str->forcedmode = get_string("forcedmode");
2517 $str->groupsnone = get_string("groupsnone");
2518 $str->groupsseparate = get_string("groupsseparate");
2519 $str->groupsvisible = get_string("groupsvisible");
2520 $sesskey = sesskey();
2523 if ($section >= 0) {
2524 $section = '&amp;sr='.$section; // Section return
2525 } else {
2526 $section = '';
2529 if ($absolute) {
2530 $path = $CFG->wwwroot.'/course';
2531 } else {
2532 $path = '.';
2535 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
2536 if ($mod->visible) {
2537 $hideshow = '<a class="editing_hide" title="'.$str->hide.'" href="'.$path.'/mod.php?hide='.$mod->id.
2538 '&amp;sesskey='.$sesskey.$section.'"><img'.
2539 ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" '.
2540 ' alt="'.$str->hide.'" /></a>'."\n";
2541 } else {
2542 $hideshow = '<a class="editing_show" title="'.$str->show.'" href="'.$path.'/mod.php?show='.$mod->id.
2543 '&amp;sesskey='.$sesskey.$section.'"><img'.
2544 ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" '.
2545 ' alt="'.$str->show.'" /></a>'."\n";
2547 } else {
2548 $hideshow = '';
2551 if ($mod->groupmode !== false) {
2552 if ($mod->groupmode == SEPARATEGROUPS) {
2553 $grouptitle = $str->groupsseparate;
2554 $groupclass = 'editing_groupsseparate';
2555 $groupimage = $CFG->pixpath.'/t/groups.gif';
2556 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=0&amp;sesskey='.$sesskey;
2557 } else if ($mod->groupmode == VISIBLEGROUPS) {
2558 $grouptitle = $str->groupsvisible;
2559 $groupclass = 'editing_groupsvisible';
2560 $groupimage = $CFG->pixpath.'/t/groupv.gif';
2561 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=1&amp;sesskey='.$sesskey;
2562 } else {
2563 $grouptitle = $str->groupsnone;
2564 $groupclass = 'editing_groupsnone';
2565 $groupimage = $CFG->pixpath.'/t/groupn.gif';
2566 $grouplink = $path.'/mod.php?id='.$mod->id.'&amp;groupmode=2&amp;sesskey='.$sesskey;
2568 if ($mod->groupmodelink) {
2569 $groupmode = '<a class="'.$groupclass.'" title="'.$grouptitle.' ('.$str->clicktochange.')" href="'.$grouplink.'">'.
2570 '<img src="'.$groupimage.'" class="iconsmall" '.
2571 'alt="'.$grouptitle.'" /></a>';
2572 } else {
2573 $groupmode = '<img title="'.$grouptitle.' ('.$str->forcedmode.')" '.
2574 ' src="'.$groupimage.'" class="iconsmall" '.
2575 'alt="'.$grouptitle.'" />';
2577 } else {
2578 $groupmode = "";
2581 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2582 if ($moveselect) {
2583 $move = '<a class="editing_move" title="'.$str->move.'" href="'.$path.'/mod.php?copy='.$mod->id.
2584 '&amp;sesskey='.$sesskey.$section.'"><img'.
2585 ' src="'.$CFG->pixpath.'/t/move.gif" class="iconsmall" '.
2586 ' alt="'.$str->move.'" /></a>'."\n";
2587 } else {
2588 $move = '<a class="editing_moveup" title="'.$str->moveup.'" href="'.$path.'/mod.php?id='.$mod->id.
2589 '&amp;move=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2590 ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" '.
2591 ' alt="'.$str->moveup.'" /></a>'."\n".
2592 '<a class="editing_movedown" title="'.$str->movedown.'" href="'.$path.'/mod.php?id='.$mod->id.
2593 '&amp;move=1&amp;sesskey='.$sesskey.$section.'"><img'.
2594 ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" '.
2595 ' alt="'.$str->movedown.'" /></a>'."\n";
2597 } else {
2598 $move = '';
2601 $leftright = '';
2602 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $mod->course))) {
2604 if (right_to_left()) { // Exchange arrows on RTL
2605 $rightarrow = 'left.gif';
2606 $leftarrow = 'right.gif';
2607 } else {
2608 $rightarrow = 'right.gif';
2609 $leftarrow = 'left.gif';
2612 if ($indent > 0) {
2613 $leftright .= '<a class="editing_moveleft" title="'.$str->moveleft.'" href="'.$path.'/mod.php?id='.$mod->id.
2614 '&amp;indent=-1&amp;sesskey='.$sesskey.$section.'"><img'.
2615 ' src="'.$CFG->pixpath.'/t/'.$leftarrow.'" class="iconsmall" '.
2616 ' alt="'.$str->moveleft.'" /></a>'."\n";
2618 if ($indent >= 0) {
2619 $leftright .= '<a class="editing_moveright" title="'.$str->moveright.'" href="'.$path.'/mod.php?id='.$mod->id.
2620 '&amp;indent=1&amp;sesskey='.$sesskey.$section.'"><img'.
2621 ' src="'.$CFG->pixpath.'/t/'.$rightarrow.'" class="iconsmall" '.
2622 ' alt="'.$str->moveright.'" /></a>'."\n";
2626 return '<span class="commands">'."\n".$leftright.$move.
2627 '<a class="editing_update" title="'.$str->update.'" href="'.$path.'/mod.php?update='.$mod->id.
2628 '&amp;sesskey='.$sesskey.$section.'"><img'.
2629 ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" '.
2630 ' alt="'.$str->update.'" /></a>'."\n".
2631 '<a class="editing_delete" title="'.$str->delete.'" href="'.$path.'/mod.php?delete='.$mod->id.
2632 '&amp;sesskey='.$sesskey.$section.'"><img'.
2633 ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" '.
2634 ' alt="'.$str->delete.'" /></a>'."\n".$hideshow.$groupmode."\n".'</span>';
2638 * given a course object with shortname & fullname, this function will
2639 * truncate the the number of chars allowed and add ... if it was too long
2641 function course_format_name ($course,$max=100) {
2643 $str = $course->shortname.': '. $course->fullname;
2644 if (strlen($str) <= $max) {
2645 return $str;
2647 else {
2648 return substr($str,0,$max-3).'...';
2653 * This function will return true if the given course is a child course at all
2655 function course_in_meta ($course) {
2656 return record_exists("course_meta","child_course",$course->id);
2661 * Print standard form elements on module setup forms in mod/.../mod.html
2663 function print_standard_coursemodule_settings($form, $features=null) {
2664 if (! $course = get_record('course', 'id', $form->course)) {
2665 error("This course doesn't exist");
2667 print_groupmode_setting($form, $course);
2668 if (!empty($features->groupings)) {
2669 print_grouping_settings($form, $course);
2671 print_visible_setting($form, $course);
2675 * Print groupmode form element on module setup forms in mod/.../mod.html
2677 function print_groupmode_setting($form, $course=NULL) {
2679 if (empty($course)) {
2680 if (! $course = get_record('course', 'id', $form->course)) {
2681 error("This course doesn't exist");
2684 if ($form->coursemodule) {
2685 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2686 error("This course module doesn't exist");
2688 $groupmode = groups_get_activity_groupmode($cm);
2689 } else {
2690 $cm = null;
2691 $groupmode = groups_get_course_groupmode($course);
2693 if ($course->groupmode or (!$course->groupmodeforce)) {
2694 echo '<tr valign="top">';
2695 echo '<td align="right"><b>'.get_string('groupmode').':</b></td>';
2696 echo '<td align="left">';
2697 $choices = array();
2698 $choices[NOGROUPS] = get_string('groupsnone');
2699 $choices[SEPARATEGROUPS] = get_string('groupsseparate');
2700 $choices[VISIBLEGROUPS] = get_string('groupsvisible');
2701 choose_from_menu($choices, 'groupmode', $groupmode, '', '', 0, false, $course->groupmodeforce);
2702 helpbutton('groupmode', get_string('groupmode'));
2703 echo '</td></tr>';
2708 * Print groupmode form element on module setup forms in mod/.../mod.html
2710 function print_grouping_settings($form, $course=NULL) {
2712 if (empty($course)) {
2713 if (! $course = get_record('course', 'id', $form->course)) {
2714 error("This course doesn't exist");
2717 if ($form->coursemodule) {
2718 if (! $cm = get_record('course_modules', 'id', $form->coursemodule)) {
2719 error("This course module doesn't exist");
2721 } else {
2722 $cm = null;
2725 $groupings = get_records_menu('groupings', 'courseid', $course->id, 'name', 'id, name');
2726 if (!empty($groupings)) {
2727 echo '<tr valign="top">';
2728 echo '<td align="right"><b>'.get_string('grouping', 'group').':</b></td>';
2729 echo '<td align="left">';
2731 $groupings;
2732 $groupingid = isset($cm->groupingid) ? $cm->groupingid : 0;
2734 choose_from_menu($groupings, 'groupingid', $groupingid, get_string('none'), '', 0, false);
2735 echo '</td></tr>';
2737 $checked = empty($cm->groupmembersonly) ? '':'checked="checked"';
2738 echo '<tr valign="top">';
2739 echo '<td align="right"><b>'.get_string('groupmembersonly', 'group').':</b></td>';
2740 echo '<td align="left">';
2741 echo "<input type=\"checkbox\" name=\"groupmembersonly\" value=\"1\" $checked />";
2742 echo '</td></tr>';
2748 * Print visibility setting form element on module setup forms in mod/.../mod.html
2750 function print_visible_setting($form, $course=NULL) {
2751 if (empty($course)) {
2752 if (! $course = get_record('course', 'id', $form->course)) {
2753 error("This course doesn't exist");
2756 if ($form->coursemodule) {
2757 $visible = get_field('course_modules', 'visible', 'id', $form->coursemodule);
2758 } else {
2759 $visible = true;
2762 if ($form->mode == 'add') { // in this case $form->section is the section number, not the id
2763 $hiddensection = !get_field('course_sections', 'visible', 'section', $form->section, 'course', $form->course);
2764 } else {
2765 $hiddensection = !get_field('course_sections', 'visible', 'id', $form->section);
2767 if ($hiddensection) {
2768 $visible = false;
2771 echo '<tr valign="top">';
2772 echo '<td align="right"><b>'.get_string('visible', '').':</b></td>';
2773 echo '<td align="left">';
2774 $choices = array(1 => get_string('show'), 0 => get_string('hide'));
2775 choose_from_menu($choices, 'visible', $visible, '', '', 0, false, $hiddensection);
2776 echo '</td></tr>';
2779 function update_restricted_mods($course,$mods) {
2781 /// Delete all the current restricted list
2782 delete_records('course_allowed_modules','course',$course->id);
2784 if (empty($course->restrictmodules)) {
2785 return; // We're done
2788 /// Insert the new list of restricted mods
2789 foreach ($mods as $mod) {
2790 if ($mod == 0) {
2791 continue; // this is the 'allow none' option
2793 $am = new object();
2794 $am->course = $course->id;
2795 $am->module = $mod;
2796 insert_record('course_allowed_modules',$am);
2801 * This function will take an int (module id) or a string (module name)
2802 * and return true or false, whether it's allowed in the given course (object)
2803 * $mod is not allowed to be an object, as the field for the module id is inconsistent
2804 * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
2807 function course_allowed_module($course,$mod) {
2809 if (empty($course->restrictmodules)) {
2810 return true;
2813 // Admins and admin-like people who can edit everything can also add anything.
2814 // This is a bit wierd, really. I debated taking it out but it's enshrined in help for the setting.
2815 if (has_capability('moodle/course:update', get_context_instance(CONTEXT_SYSTEM))) {
2816 return true;
2819 if (is_numeric($mod)) {
2820 $modid = $mod;
2821 } else if (is_string($mod)) {
2822 $modid = get_field('modules','id','name',$mod);
2824 if (empty($modid)) {
2825 return false;
2828 return (record_exists('course_allowed_modules','course',$course->id,'module',$modid));
2832 * Recursively delete category including all subcategories and courses.
2833 * @param object $ccategory
2834 * @return bool status
2836 function category_delete_full($category, $showfeedback=true) {
2837 global $CFG;
2838 require_once($CFG->libdir.'/gradelib.php');
2839 require_once($CFG->libdir.'/questionlib.php');
2841 if ($children = get_records('course_categories', 'parent', $category->id, 'sortorder ASC')) {
2842 foreach ($children as $childcat) {
2843 if (!category_delete_full($childcat, $showfeedback)) {
2844 notify("Error deleting category $childcat->name");
2845 return false;
2850 if ($courses = get_records('course', 'category', $category->id, 'sortorder ASC')) {
2851 foreach ($courses as $course) {
2852 if (!delete_course($course->id, false)) {
2853 notify("Error deleting course $course->shortname");
2854 return false;
2856 notify(get_string('coursedeleted', '', $course->shortname), 'notifysuccess');
2860 // now delete anything that may depend on course category context
2861 grade_course_category_delete($category->id, 0, $showfeedback);
2862 if (!question_delete_course_category($category, 0, $showfeedback)) {
2863 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2864 return false;
2867 // finally delete the category and it's context
2868 delete_records('course_categories', 'id', $category->id);
2869 delete_context(CONTEXT_COURSECAT, $category->id);
2871 events_trigger('course_category_deleted', $category);
2873 notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
2875 return true;
2879 * Delete category, but move contents to another category.
2880 * @param object $ccategory
2881 * @param int $newparentid category id
2882 * @return bool status
2884 function category_delete_move($category, $newparentid, $showfeedback=true) {
2885 global $CFG;
2886 require_once($CFG->libdir.'/gradelib.php');
2887 require_once($CFG->libdir.'/questionlib.php');
2889 if (!$newparentcat = get_record('course_categories', 'id', $newparentid)) {
2890 return false;
2893 if ($children = get_records('course_categories', 'parent', $category->id, 'sortorder ASC')) {
2894 foreach ($children as $childcat) {
2895 if (!move_category($childcat, $newparentcat)) {
2896 notify("Error moving category $childcat->name");
2897 return false;
2902 if ($courses = get_records('course', 'category', $category->id, 'sortorder ASC', 'id')) {
2903 if (!move_courses(array_keys($courses), $newparentid)) {
2904 notify("Error moving courses");
2905 return false;
2907 notify(get_string('coursesmovedout', '', format_string($category->name)), 'notifysuccess');
2910 // now delete anything that may depend on course category context
2911 grade_course_category_delete($category->id, $newparentid, $showfeedback);
2912 if (!question_delete_course_category($category, $newparentcat, $showfeedback)) {
2913 notify(get_string('errordeletingquestionsfromcategory', 'question', $category), 'notifysuccess');
2914 return false;
2917 // finally delete the category and it's context
2918 delete_records('course_categories', 'id', $category->id);
2919 delete_context(CONTEXT_COURSECAT, $category->id);
2921 events_trigger('course_category_deleted', $category);
2923 notify(get_string('coursecategorydeleted', '', format_string($category->name)), 'notifysuccess');
2925 return true;
2928 /***
2929 *** Efficiently moves many courses around while maintaining
2930 *** sortorder in order.
2932 *** $courseids is an array of course ids
2936 function move_courses ($courseids, $categoryid) {
2938 global $CFG;
2940 if (!empty($courseids)) {
2942 $courseids = array_reverse($courseids);
2944 foreach ($courseids as $courseid) {
2946 if (! $course = get_record("course", "id", $courseid)) {
2947 notify("Error finding course $courseid");
2948 } else {
2949 // figure out a sortorder that we can use in the destination category
2950 $sortorder = get_field_sql('SELECT MIN(sortorder)-1 AS min
2951 FROM ' . $CFG->prefix . 'course WHERE category=' . $categoryid);
2952 if (is_null($sortorder) || $sortorder === false) {
2953 // the category is empty
2954 // rather than let the db default to 0
2955 // set it to > 100 and avoid extra work in fix_coursesortorder()
2956 $sortorder = 200;
2957 } else if ($sortorder < 10) {
2958 fix_course_sortorder($categoryid);
2961 $course->category = $categoryid;
2962 $course->sortorder = $sortorder;
2963 $course->fullname = addslashes($course->fullname);
2964 $course->shortname = addslashes($course->shortname);
2965 $course->summary = addslashes($course->summary);
2966 $course->password = addslashes($course->password);
2967 $course->teacher = addslashes($course->teacher);
2968 $course->teachers = addslashes($course->teachers);
2969 $course->student = addslashes($course->student);
2970 $course->students = addslashes($course->students);
2972 if (!update_record('course', $course)) {
2973 notify("An error occurred - course not moved!");
2976 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2977 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2978 context_moved($context, $newparent);
2981 fix_course_sortorder();
2983 return true;
2986 /***
2987 *** Efficiently moves a category - NOTE that this can have
2988 *** a huge impact access-control-wise...
2992 function move_category ($category, $newparentcat) {
2994 global $CFG;
2996 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
2998 if (empty($newparentcat->id)) {
2999 if (!set_field('course_categories', 'parent', 0, 'id', $category->id)) {
3000 return false;
3002 $newparent = get_context_instance(CONTEXT_SYSTEM);
3003 } else {
3004 if (!set_field('course_categories', 'parent', $newparentcat->id, 'id', $category->id)) {
3005 return false;
3007 $newparent = get_context_instance(CONTEXT_COURSECAT, $newparentcat->id);
3010 context_moved($context, $newparent);
3012 // The most effective thing would be to find the common parent,
3013 // until then, do it sitewide...
3014 fix_course_sortorder();
3017 return true;
3021 * @param string $format Course format ID e.g. 'weeks'
3022 * @return Name that the course format prefers for sections
3024 function get_section_name($format) {
3025 $sectionname = get_string("name$format","format_$format");
3026 if($sectionname == "[[name$format]]") {
3027 $sectionname = get_string("name$format");
3029 return $sectionname;
3033 * Can the current user delete this course?
3034 * @param int $courseid
3035 * @return boolean
3037 * Exception here to fix MDL-7796.
3039 * FIXME
3040 * Course creators who can manage activities in the course
3041 * shoule be allowed to delete the course. We do it this
3042 * way because we need a quick fix to bring the functionality
3043 * in line with what we had pre-roles. We can't give the
3044 * default course creator role moodle/course:delete at
3045 * CONTEXT_SYSTEM level because this will allow them to
3046 * delete any course in the site. So we hard code this here
3047 * for now.
3049 * @author vyshane AT gmail.com
3051 function can_delete_course($courseid) {
3053 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3055 return ( has_capability('moodle/course:delete', $context)
3056 || (has_capability('moodle/legacy:coursecreator', $context)
3057 && has_capability('moodle/course:manageactivities', $context)) );
3062 * Create a course and either return a $course object or false
3064 * @param object $data - all the data needed for an entry in the 'course' table
3066 function create_course($data) {
3067 global $CFG, $USER;
3069 // preprocess allowed mods
3070 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
3071 unset($data->allowedmods);
3072 if ($CFG->restrictmodulesfor == 'all') {
3073 $data->restrictmodules = 1;
3074 } else {
3075 $data->restrictmodules = 0;
3078 $data->timecreated = time();
3080 // place at beginning of category
3081 fix_course_sortorder();
3082 $data->sortorder = get_field_sql("SELECT min(sortorder)-1 FROM {$CFG->prefix}course WHERE category=$data->category");
3083 if (empty($data->sortorder)) {
3084 $data->sortorder = 100;
3087 if ($newcourseid = insert_record('course', $data)) { // Set up new course
3089 $course = get_record('course', 'id', $newcourseid);
3091 // Setup the blocks
3092 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
3093 blocks_repopulate_page($page); // Return value not checked because you can always edit later
3095 update_restricted_mods($course, $allowedmods);
3097 $section = new object();
3098 $section->course = $course->id; // Create a default section.
3099 $section->section = 0;
3100 $section->id = insert_record('course_sections', $section);
3102 fix_course_sortorder();
3104 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
3106 //trigger events
3107 events_trigger('course_created', $course);
3109 return $course;
3112 return false; // error
3117 * Update a course and return true or false
3119 * @param object $data - all the data needed for an entry in the 'course' table
3121 function update_course($data) {
3122 global $USER, $CFG;
3124 // Preprocess allowed mods
3125 $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods;
3126 unset($data->allowedmods);
3128 // Normal teachers can't change setting
3129 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3130 unset($data->restrictmodules);
3133 $movecat = false;
3134 $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above
3135 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category))
3136 or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) {
3137 // can not move to new category, keep the old one
3138 unset($data->category);
3139 } elseif ($oldcourse->category != $data->category) {
3140 $movecat = true;
3143 // Update with the new data
3144 if (update_record('course', $data)) {
3146 $course = get_record('course', 'id', $data->id);
3148 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
3150 // "Admins" can change allowed mods for a course
3151 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
3152 update_restricted_mods($course, $allowedmods);
3155 if ($movecat) {
3156 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3157 $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category);
3158 context_moved($context, $newparent);
3161 fix_course_sortorder();
3163 // Test for and remove blocks which aren't appropriate anymore
3164 $page = page_create_object(PAGE_COURSE_VIEW, $course->id);
3165 blocks_remove_inappropriate($page);
3167 // put custom role names into db
3168 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3170 foreach ($data as $dname => $dvalue) {
3172 // is this the right param?
3173 $dvalue = clean_param($dvalue, PARAM_NOTAGS);
3175 if (!strstr($dname, 'role_')) {
3176 continue;
3179 $dt = explode('_', $dname);
3180 $roleid = $dt[1];
3181 // make up our mind whether we want to delete, update or insert
3183 if (empty($dvalue)) {
3185 delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid);
3187 } else if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) {
3189 $t->name = $dvalue;
3190 update_record('role_names', $t);
3192 } else {
3194 $t->contextid = $context->id;
3195 $t->roleid = $roleid;
3196 $t->name = $dvalue;
3197 insert_record('role_names', $t);
3201 //trigger events
3202 events_trigger('course_updated', $course);
3204 return true;
3208 return false;